/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2014 Olaf Wintermann. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#import <stdio.h>
#import <stdlib.h>
#import <string.h>
#import <stdarg.h>

#import "menu.h"
#import "window.h"
#import "stock.h"

@implementation UiMenuDelegate 

- (UiMenuDelegate*) init {
    items = NULL;
    itemlists = NULL;
    return self;
}

- (void) menuNeedsUpdate:(NSMenu *) menu {
    NSWindow *activeWindow = [NSApp keyWindow];
    [(UiCocoaWindow*)activeWindow updateMenu: menu];
}

- (void) addItem:(NSMenuItem*) item var: (char*)name {
    UiStateItem *i = malloc(sizeof(UiStateItem));
    i->item = item;
    i->var = name;
    items = ucx_list_append(items, i);
}

- (void) addList:(UiList*) list menu:(NSMenu*)menu index: (int)i callback: (ui_callback)f data:(void*) data {
    UiMenuItemList *itemList = malloc(sizeof(UiMenuItemList));
    itemList->list = list;
    itemList->menu = menu;
    itemList->first = NULL;
    itemList->index = i;
    itemList->oldcount = 0;
    itemList->callback = f;
    itemList->data = data;
    itemlists = ucx_list_append(itemlists, itemList);
}

- (UcxList*) items {
    return items;
}

- (UcxList*) lists {
    return itemlists;
    
}

@end


@implementation UiGroupMenuItem

- (id)initWithTitle:(NSString*)title action:(SEL)action keyEquivalent:(NSString*)s {
    [super initWithTitle:title action:action keyEquivalent:s];
    groups = [[NSMutableArray alloc]initWithCapacity: 16];
    return self;
}

- (void) addGroup:(int)group {
    NSNumber *groupNumber = [NSNumber numberWithInteger:group];
    [groups addObject:groupNumber];
}

- (void) checkGroups:(int*)g count:(int)n {
    int c = [groups count];
    
    char *check = calloc(1, c);
    for(int i=0;i<n;i++) {
        for(int k=0;k<c;k++) {
            NSNumber *groupNumber = [groups objectAtIndex:k];
            if([groupNumber intValue] == g[i]) {
                check[k] = 1;
                break;
            }
        }
    }
    free(groups);
    
    for(int j=0;j<c;j++) {
        if(check[j] == 0) {
            [self setEnabled:NO];
            return;
        }
    }
    [self setEnabled:YES];
}

@end


static NSMenu *currentMenu = NULL;
static int currentItemIndex = 0;
static UiMenuDelegate *delegate;

void ui_menu_init() {
    delegate = [[UiMenuDelegate alloc]init];
}

UiMenuDelegate* ui_menu_delegate() {
    return delegate;
}


void ui_menu(char *title) {
    NSString *str = [[NSString alloc] initWithUTF8String:title];
    
    NSMenu *menu = [[NSMenu alloc] initWithTitle: str];
    NSMenuItem *menuItem = [[NSApp mainMenu] addItemWithTitle:str
                                                       action:nil keyEquivalent:@""];
    [menu setDelegate: delegate];
    [menu setAutoenablesItems:NO];
    
    [[NSApp mainMenu] setSubmenu:menu forItem:menuItem];
    currentMenu = menu;
    currentItemIndex = 0;
}

void ui_menuitem(char *label, ui_callback f, void *data) {
    ui_menuitem_gr(label, f, data, -1);
}

void ui_menuitem_st(char *stockid, ui_callback f, void *data) {
    ui_menuitem_stgr(stockid, f, data, -1);
}

void ui_menuitem_gr(char *label, ui_callback f, void *userdata, ...) {
    // create menu item
    EventWrapper *event = [[EventWrapper alloc]initWithData:userdata callback:f];
    NSString *title = [[NSString alloc] initWithUTF8String:label];
    UiGroupMenuItem *item = [[UiGroupMenuItem alloc]initWithTitle:title action:@selector(handleEvent:) keyEquivalent:@""];
    [item setTarget:event];
    
    // add groups
    va_list ap;
    va_start(ap, userdata);
    int group;
    while((group = va_arg(ap, int)) != -1) {
        [item addGroup: group];
    }
    va_end(ap);
    
    [currentMenu addItem:item];
    
    currentItemIndex++;
}

void ui_menuitem_stgr(char *stockid, ui_callback f, void *userdata, ...) {
    // create menu item
    EventWrapper *event = [[EventWrapper alloc]initWithData:userdata callback:f];
    UiStockItem *si = ui_get_stock_item(stockid);
    UiGroupMenuItem *item = [[UiGroupMenuItem alloc]initWithTitle:si->label
                                action:@selector(handleEvent:)
                                keyEquivalent:si->keyEquivalent];
    [item setTarget:event];
    
    // add groups
    va_list ap;
    va_start(ap, userdata);
    int group;
    while((group = va_arg(ap, int)) != -1) {
        [item addGroup: group];
    }
    va_end(ap);
    
    [currentMenu addItem:item];
    
    currentItemIndex++;
}

void ui_checkitem(char *label, ui_callback f, void *data) {
    EventWrapper *event = [[EventWrapper alloc]initWithData:data callback:f];
    NSString *str = [[NSString alloc] initWithUTF8String:label];
    
    NSMenuItem *item = [currentMenu addItemWithTitle:str
                                              action:@selector(handleStateEvent:) keyEquivalent:@""];
    [item setTarget:event];
    
    [delegate addItem: item var:NULL];
    currentItemIndex++;
}

void ui_checkitem_nv(char *label, char *vname) {
    EventWrapper *event = [[EventWrapper alloc]initWithData:NULL callback:NULL];
    NSString *str = [[NSString alloc] initWithUTF8String:label];
    
    NSMenuItem *item = [currentMenu addItemWithTitle:str
                                              action:@selector(handleStateEvent:) keyEquivalent:@""];
    [item setTarget:event];
    
    [delegate addItem: item var:vname];
    currentItemIndex++;
}

void ui_menuseparator() {
    [currentMenu addItem: [NSMenuItem separatorItem]];
    currentItemIndex++;
}

void ui_menuitem_list (UiList *items, ui_callback f, void *data) {
    [delegate addList:items menu:currentMenu index:currentItemIndex callback:f data:data];
}



int ui_menuitem_get(UiInteger *i) {
    UiMenuItem *item = i->obj;
    i->value = [item->item state];
    return i->value;
}

void ui_menuitem_set(UiInteger *i, int value) {
    UiMenuItem *item = i->obj;
    [item->item setState: value];
    i->value = value;
    item->state = value;
}


int ui_update_item(UiCocoaWindow *window, void *data) {
    UiMenuItem *item = data;
    [item->item setState: item->state];
    return 0;
}

int ui_update_item_list(UiCocoaWindow *window, void *data) {
    UiMenuItemList *itemList = data;
    UiList *list = itemList->list;
    
    for(int r=0;r<itemList->oldcount;r++) {
        [itemList->menu removeItemAtIndex:itemList->index];
    }
    
    char *str = ui_list_first(list);
    int i = itemList->index;
    [itemList->menu insertItem: [NSMenuItem separatorItem] atIndex: i];
    i++;
    while(str) {
        EventWrapper *event = [[EventWrapper alloc]initWithData:itemList->data callback:itemList->callback];
        [event setIntval: i - itemList->index - 1];
        
        NSString *title = [[NSString alloc] initWithUTF8String:str];
        NSMenuItem *item = [[NSMenuItem alloc]initWithTitle:title action:@selector(handleEvent:) keyEquivalent:@""];
        [item setTarget:event];
        
        [itemList->menu insertItem:item atIndex:i];
        
        str = ui_list_next(list);
        i++;
    }
    
    itemList->oldcount = i - itemList->index;
    
    return 0;
}
