/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2024 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 "button.h"
#import "EventData.h"
#import "Container.h"
#import <objc/runtime.h>

UIWIDGET ui_button_create(UiObject* obj, UiButtonArgs *args) {
    NSButton *button = [[NSButton alloc] init];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    if(args->label) {
        NSString *label = [[NSString alloc] initWithUTF8String:args->label];
        button.title = label;
    }
    
    if(args->onclick) {
        EventData *event = [[EventData alloc] init:args->onclick userdata:args->onclickdata];
        event.obj = obj;
        button.target = event;
        button.action = @selector(handleEvent:);
        objc_setAssociatedObject(button, "eventdata", event, OBJC_ASSOCIATION_RETAIN);
    }
    
    UiLayout layout = UI_INIT_LAYOUT(args);
    ui_container_add(obj, button, &layout);
    
    return (__bridge void*)button;
}


static void togglebutton_eventdata(id button, UiVar *var, void **eventdata, int *value) {
    NSButton *btn = (NSButton*)button;
    NSControlStateValue state = btn.state;
    *value = (int)state;
}

UIWIDGET togglebutton_create(UiObject* obj, UiToggleArgs *args, enum NSButtonType type) {
    NSButton *button = [[NSButton alloc] init];
    [button setButtonType:type];
    //[button setAllowsMixedState:YES];
    
    if(args->label) {
        NSString *label = [[NSString alloc] initWithUTF8String:args->label];
        button.title = label;
    }
    
    UiVar* var = uic_widget_var(obj->ctx, obj->ctx, args->value, args->varname, UI_VAR_INTEGER);
    if(var) {
        UiInteger *i = var->value;
        i->obj = (__bridge void*)button;
        i->get = ui_togglebutton_get;
        i->set = ui_togglebutton_set;
    }
    
    if(args->onchange) {
        EventData *event = [[EventData alloc] init:args->onchange userdata:args->onchangedata];
        event.get_eventdata = togglebutton_eventdata;
        event.obj = obj;
        event.var = var;
        event.vartype = UI_VAR_INTEGER;
        button.target = event;
        button.action = @selector(handleEventWithEventData:);
        objc_setAssociatedObject(button, "eventdata", event, OBJC_ASSOCIATION_RETAIN);
    }
    
    UiLayout layout = UI_INIT_LAYOUT(args);
    ui_container_add(obj, button, &layout);
    
    return (__bridge void*)button;
}

int64_t ui_togglebutton_get(UiInteger *i) {
    NSButton *button = (__bridge NSButton*)i->obj;
    NSControlStateValue state = button.state;
    i->value = (int64_t)state;
    return (int64_t)state;
}

void ui_togglebutton_set(UiInteger *i, int64_t value) {
    NSButton *button = (__bridge NSButton*)i->obj;
    NSControlStateValue state;
    switch(value) {
        case 0: state = NSControlStateValueOff; break;
        case 1: state = NSControlStateValueOff; break;
        default: state = NSControlStateValueMixed;
    }
    i->value = (int64_t)state;
    button.state = state;
}

UIWIDGET ui_togglebutton_create(UiObject* obj, UiToggleArgs *args) {
    return togglebutton_create(obj, args, NSButtonTypePushOnPushOff);
}

UIWIDGET ui_checkbox_create(UiObject* obj, UiToggleArgs *args) {
    return togglebutton_create(obj, args, NSButtonTypeSwitch);
}

static void switch_eventdata(id button, UiVar *var, void **eventdata, int *value) {
    NSSwitch *btn = (NSSwitch*)button;
    NSControlStateValue state = btn.state;
    *value = (int)state;
}

UIWIDGET ui_switch_create(UiObject* obj, UiToggleArgs *args) {
    NSSwitch *button = [[NSSwitch alloc] init];
    
    UiVar* var = uic_widget_var(obj->ctx, obj->ctx, args->value, args->varname, UI_VAR_INTEGER);
    if(var) {
        UiInteger *i = var->value;
        i->obj = (__bridge void*)button;
        i->get = ui_switch_get;
        i->set = ui_switch_set;
    }
    
    if(args->onchange) {
        EventData *event = [[EventData alloc] init:args->onchange userdata:args->onchangedata];
        event.get_eventdata = switch_eventdata;
        event.obj = obj;
        event.var = var;
        event.vartype = UI_VAR_INTEGER;
        button.target = event;
        button.action = @selector(handleEventWithEventData:);
        objc_setAssociatedObject(button, "eventdata", event, OBJC_ASSOCIATION_RETAIN);
    }
    
    UiLayout layout = UI_INIT_LAYOUT(args);
    ui_container_add(obj, button, &layout);
    
    return (__bridge void*)button;
}

int64_t ui_switch_get(UiInteger *i) {
    NSSwitch *button = (__bridge NSSwitch*)i->obj;
    NSControlStateValue state = button.state;
    i->value = (int64_t)state;
    return (int64_t)state;
}

void ui_switch_set(UiInteger *i, int64_t value) {
    NSSwitch *button = (__bridge NSSwitch*)i->obj;
    NSControlStateValue state;
    switch(value) {
        case 0: state = NSControlStateValueOff; break;
        case 1: state = NSControlStateValueOff; break;
        default: state = NSControlStateValueMixed;
    }
    i->value = (int64_t)state;
    button.state = state;
}


@implementation UiRadioButton

- (UiRadioButton*)init {
    self = [super init];
    _direct_state = NO;
    [self setButtonType:NSButtonTypeRadio];
    return self;
}

- (void)setState:(NSControlStateValue)state {
    // NOOP
}

@end

static void radiobutton_eventdata(id button, UiVar *var, void **eventdata, int *value) {
    if(var) {
        UiInteger *value = var->value;
        NSMutableArray *buttons = (__bridge NSMutableArray*)value->obj;
        for(UiRadioButton *b in buttons) {
            if(b != button) {
                b.direct_state = YES;
                [[b cell] setState:0];
                b.direct_state = NO;
            }
        }
    }
}

UIWIDGET ui_radiobutton_create(UiObject* obj, UiToggleArgs *args) {
    UiRadioButton *button = [[UiRadioButton alloc] init];
    
    if(args->label) {
        button.title = [[NSString alloc] initWithUTF8String:args->label];
    }
    
    UiVar* var = uic_widget_var(obj->ctx, obj->ctx, args->value, args->varname, UI_VAR_INTEGER);
    button.var = var;
    NSMutableArray *buttons = nil;
    if(var) {
        UiInteger *i = var->value;
        buttons = (__bridge NSMutableArray*)i->obj;
        if(!buttons) {
            buttons = [[NSMutableArray alloc] init];
            i->obj = (__bridge void*)buttons;
            i->get = ui_radiobuttons_get;
            i->set = ui_radiobuttons_set;
        }
        [buttons addObject:button];
        objc_setAssociatedObject(button, "radiogroup", buttons, OBJC_ASSOCIATION_RETAIN);
    }
    
    if(args->onchange || var) {
        EventData *event = [[EventData alloc] init:args->onchange userdata:args->onchangedata];
        event.get_eventdata = radiobutton_eventdata;
        event.obj = obj;
        event.var = var;
        event.vartype = UI_VAR_INTEGER;
        button.target = event;
        
        
        button.action = @selector(handleEventWithEventData:);
        
        objc_setAssociatedObject(button, "eventdata", event, OBJC_ASSOCIATION_RETAIN);
    }
    
    UiLayout layout = UI_INIT_LAYOUT(args);
    ui_container_add(obj, button, &layout);
    
    return (__bridge void*)button;
}

int64_t ui_radiobuttons_get(UiInteger *i) {
    NSMutableArray *buttons = (__bridge NSMutableArray*)i->obj;
    int64_t index = 0;
    for(UiRadioButton *b in buttons) {
        if([b cell].state != 0) {
            i->value = index + 1;
            break;
        }
        index++;
    }
    return i->value;
}

void ui_radiobuttons_set(UiInteger *i, int64_t value) {
    NSMutableArray *buttons = (__bridge NSMutableArray*)i->obj;
    int64_t index = 1;
    for(UiRadioButton *b in buttons) {
        if(index == value) {
            [b cell].state = NSControlStateValueOn;
        } else {
            [b cell].state = NSControlStateValueOff;
        }
        index++;
    }
}
