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

UIWIDGET ui_textarea_create(UiObject *obj, UiTextAreaArgs *args) {
    NSTextView *textview = [[NSTextView alloc] init];
    textview.autoresizingMask = NSViewWidthSizable;
    textview.minSize = NSMakeSize(0, 0);
    textview.maxSize = NSMakeSize(FLT_MAX, FLT_MAX);
    
    NSScrollView *scrollview = [[NSScrollView alloc] init];
    scrollview.hasVerticalScroller = YES;
    scrollview.documentView = textview;
    
    // store link to the textview
    // associate it with the textview and the scrollview to support both widgets in ui_textarea_gettextwidget
    objc_setAssociatedObject(textview, "ui_textarea", textview, OBJC_ASSOCIATION_ASSIGN);
    objc_setAssociatedObject(scrollview, "ui_textarea", textview, OBJC_ASSOCIATION_ASSIGN);
    
    UiLayout layout = UI_INIT_LAYOUT(args);
    ui_container_add(obj, scrollview, &layout);
    
    
    UiVar* var = uic_widget_var(obj->ctx, obj->ctx, args->value, args->varname, UI_VAR_TEXT);
    if(var) {
        UiText *text = var->value;
        text->obj = (__bridge void*)textview;
        ui_textarea_restore(text);
        
        text->save = ui_textarea_save;
        text->destroy = ui_textarea_destroy;
        text->restore = ui_textarea_restore;
        text->set = ui_textarea_set;
        text->get = ui_textarea_get;
        text->getsubstr = ui_textarea_getsubstr;
        text->insert = ui_textarea_insert;
        text->setposition = ui_textarea_setposition;
        text->position = ui_textarea_position;
        text->setselection = ui_textarea_setselection;
        text->selection = ui_textarea_selection;
        text->length = ui_textarea_length;
        text->remove = ui_textarea_remove;
    }
    
    return (__bridge void*)scrollview;
}

UIWIDGET ui_textarea_gettextwidget(UIWIDGET textarea) {
    id view = (__bridge id)textarea;
    id textview = objc_getAssociatedObject(view, "ui_textarea");
    return (__bridge void*)textview;
}



void ui_textarea_save(UiText *text) {
    
}

void ui_textarea_destroy(UiText *text) {
    (void)(__bridge_transfer NSTextStorage*)text->data1;
}

void ui_textarea_restore(UiText *text) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSTextStorage *textStorage;
    if(text->data1) {
        textStorage = (__bridge NSTextStorage*)text->data1;
    } else {
        textStorage = [[NSTextStorage alloc] init];
    }
    [textview.layoutManager replaceTextStorage:textStorage];
    text->data1 = (__bridge_retained void*)textStorage;
}

void ui_textarea_set(UiText *text, const char *str) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    if(text->value.free) {
        text->value.free(text->value.ptr);
    }
    text->value.ptr = strdup(str);
    text->value.free = free;
    textview.string = [[NSString alloc] initWithUTF8String:str];
}

char* ui_textarea_get(UiText *text) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    if(text->value.free) {
        text->value.free(text->value.ptr);
    }
    text->value.ptr = strdup(textview.string.UTF8String);
    text->value.free = free;
    return text->value.ptr;
}

char* ui_textarea_getsubstr(UiText *text, int begin, int end) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSString *str = textview.string;
    NSRange range = NSMakeRange(begin, end-begin);
    NSString *sub = [str substringWithRange:range];
    return strdup(sub.UTF8String);
}

void ui_textarea_insert(UiText *text, int pos, const char *str) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSString *s = [[NSString alloc] initWithUTF8String:str];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithString:s];
    [textview.textStorage insertAttributedString:attributedStr atIndex:pos];
}

void ui_textarea_setposition(UiText *text, int pos) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSRange range = NSMakeRange(pos, 0);
    [textview setSelectedRange:range];
}

int ui_textarea_position(UiText *text) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSRange range = textview.selectedRange;
    return (int)range.location;
}

void ui_textarea_setselection(UiText *text, int begin, int end) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSRange range = NSMakeRange(begin, end-begin);
    [textview setSelectedRange:range];
}

void ui_textarea_selection(UiText *text, int *begin, int *end) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    NSRange range = textview.selectedRange;
    if(begin) {
        *begin = (int)range.location;
    }
    if(end) {
        *end = (int)(range.location+range.length);
    }
}

int ui_textarea_length(UiText *text) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    return (int)textview.string.length;
}

void ui_textarea_remove(UiText *text, int begin, int end) {
    NSTextView *textview = (__bridge NSTextView*)text->obj;
    
    if (begin < 0 || end < begin || end > textview.string.length) {
        return;
    }
    
    NSRange range = NSMakeRange(begin, end - begin);
    [[textview textStorage] deleteCharactersInRange:range];
}



/* -------------------------- TextField -------------------------- */

static UIWIDGET textfield_create(UiObject *obj, UiTextFieldArgs *args, BOOL password, BOOL frameless) {
    NSTextField *textfield;
    if(password) {
        textfield = [[NSSecureTextField alloc] init];
    } else {
        textfield = [[NSTextField alloc] init];
    }
    
    if(!args->hfill || args->width > 0) {
        textfield.translatesAutoresizingMaskIntoConstraints = NO;
        int width = args->width > 0 ? args->width : 100;
        [[textfield.widthAnchor constraintEqualToConstant:width] setActive:YES];
    }
    
    
    if(frameless) {
        [textfield setBezeled: NO];
    }
    
    UiLayout layout = UI_INIT_LAYOUT(args);
    ui_container_add(obj, textfield, &layout);
    
    UiVar* var = uic_widget_var(obj->ctx, obj->ctx, args->value, args->varname, UI_VAR_STRING);
    if(var) {
        UiString *s = var->value;
        if(s->value.ptr) {
            textfield.stringValue = [[NSString alloc] initWithUTF8String:s->value.ptr];
            if(s->value.free) {
                s->value.free(s->value.ptr);
            }
        }
        s->obj = (__bridge void*)textfield;
        s->get = ui_textfield_get;
        s->set = ui_textfield_set;
    }
    
    return (__bridge void*)textfield;
}

UIWIDGET ui_textfield_create(UiObject *obj, UiTextFieldArgs *args) {
    return textfield_create(obj, args, FALSE, FALSE);
}

UIWIDGET ui_frameless_textfield_create(UiObject* obj, UiTextFieldArgs *args) {
    return textfield_create(obj, args, FALSE, TRUE);
}

UIWIDGET ui_passwordfield_create(UiObject* obj, UiTextFieldArgs *args) {
    return textfield_create(obj, args, TRUE, FALSE);
}

char* ui_textfield_get(UiString *s) {
    NSTextField *textfield = (__bridge NSTextField*)s->obj;
    NSString *str = textfield.stringValue;
    const char *cstr = str.UTF8String;
    if(s->value.free) {
        s->value.free(s->value.ptr);
    }
    s->value.ptr = strdup(cstr);
    s->value.free = free;
    return s->value.ptr;
}

void ui_textfield_set(UiString *s, const char *value) {
    if(s->value.free) {
        s->value.free(s->value.ptr);
    }
    s->value.ptr = NULL;
    s->value.free = NULL;
    NSTextField *textfield = (__bridge NSTextField*)s->obj;
    textfield.stringValue = [[NSString alloc] initWithUTF8String:value];
}

/* -------------------------- public Textfield functions -------------------------- */

void ui_textfield_focus(UIWIDGET textfield) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    [tf.window makeFirstResponder:tf];
    [tf selectText:nil];
}

void ui_textfield_focus_without_selecting(UIWIDGET textfield) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    [tf.window makeFirstResponder:tf];
}

void ui_textfield_set_selection(UIWIDGET textfield, int begin, int end) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    [tf.window makeFirstResponder:tf];
    NSTextView *fieldEditor = (NSTextView *)[tf.window fieldEditor:YES forObject:tf];
    [fieldEditor setSelectedRange:NSMakeRange(begin, end-begin)];
}

void ui_textfield_select_all(UIWIDGET textfield) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    [tf selectText:nil];
}

void ui_textfield_set_editable(UIWIDGET textfield, UiBool editable) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    tf.editable = editable;
}

UiBool ui_textfield_is_editable(UIWIDGET textfield) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    return tf.isEditable;
}

void ui_textfield_set_position(UIWIDGET textfield, int pos) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    NSTextView *editor = (NSTextView *)[tf currentEditor];
    [editor setSelectedRange:NSMakeRange(pos, 0)];
}

int ui_textfield_get_position(UIWIDGET textfield) {
    NSTextField *tf = (__bridge NSTextField*)textfield;
    NSTextView *editor = (NSTextView *)[tf currentEditor];
    NSRange selectedRange = [editor selectedRange];
    return (int)selectedRange.location;
}
