/*
 * 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 "toolkit.h"

#include <stdlib.h>
#include <string.h>

#include "../common/document.h"
#include "../common/properties.h"
#include "../common/menu.h"
#include "../common/toolbar.h"
#include "../common/threadpool.h"
#include "../common/app.h"

#import "image.h"
#import "menu.h"
#import "Toolbar.h"
#import "UiThread.h"

#import "AppDelegate.h"

static const char *application_name;

static int app_argc;
static const char **app_argv;

static UiBool exit_on_shutdown;

static char *main_thread_error_msg;

// This function is only used by language bindings, to improve error messages
// for example, when using java bindings, this can provide infos how to fix
// this (-XstartOnFirstThread)
void ui_set_main_thread_error_msg(const char *msg) {
    main_thread_error_msg = msg ? strdup(msg) : NULL;
}

/* ------------------- App Init / Event Loop functions ------------------- */

static AppDelegate *app_delegate;

static void main_thr_check(const char *func) {
    if(![NSThread isMainThread]) {
        fprintf(stderr, "Error: %s must run on the main thread.\n", func);
        if(main_thread_error_msg) {
            fprintf(stderr, "%s\n", main_thread_error_msg);
        }
        exit(1);
    }
}

void ui_init(const char *appname, int argc, char **argv) {
    main_thr_check("ui_init");
    
    application_name = appname ? strdup(appname) : NULL;
    app_argc = argc;
    app_argv = (const char**)argv;
    
    uic_init_global_context();
    
    uic_menu_init();
    uic_toolbar_init();
    
    uic_load_app_properties();
    
    NSApplication *app = [NSApplication sharedApplication];
    [app setActivationPolicy:NSApplicationActivationPolicyRegular];
    
    //[NSBundle loadNibNamed:@"MainMenu" owner:NSApp ];
    //[[NSBundle mainBundle] loadNibNamed:@"MainMenu" owner:NSApp topLevelObjects:&topLevelObjects];
    
    app_delegate = [[AppDelegate alloc] init];
    
    fflush(stdout);
    app.delegate = app_delegate;
    
    
    ui_icon_init();
    ui_toolbar_init();
    
}

const char* ui_appname(void) {
    return application_name;
}

void ui_app_exit_on_shutdown(UiBool exitapp) {
    exit_on_shutdown = exitapp;
}

void ui_cocoa_onstartup(void) {
    UiEvent e;
    e.obj = NULL;
    e.window = NULL;
    e.document = NULL;
    e.eventdata = NULL;
    e.intval = 0;
    uic_application_startup(&e);
}

void ui_cocoa_onopen(const char *file) {
    UiEvent e;
    e.obj = NULL;
    e.window = NULL;
    e.document = NULL;
    e.eventdata = NULL;
    e.intval = 0;
    uic_application_open(&e);
}

void ui_cocoa_onexit(void) {
    UiEvent e;
    e.obj = NULL;
    e.window = NULL;
    e.document = NULL;
    e.eventdata = NULL;
    e.intval = 0;
    uic_application_exit(&e);
}

void ui_main(void) {
    main_thr_check("ui_main");
    
    NSApplicationMain(app_argc,app_argv);
    //[NSApp finishLaunching];
    //[NSApp activateIgnoringOtherApps:YES];
    //[NSApp run];
    if(exit_on_shutdown) {
        exit(0);
    }
}

void ui_app_ref(void) {
    // TODO
}

void ui_app_unref(void) {
    // TODO
}

void ui_app_quit(void) {
    [[NSApplication sharedApplication] terminate:nil];
}

void ui_open_uri(const char *uri) {
    NSString *urlString = [NSString stringWithUTF8String:uri];
    NSURL *url = [NSURL URLWithString:urlString];
    [[NSWorkspace sharedWorkspace] openURL:url];
}

/* ------------------- Window Visibility functions ------------------- */

void ui_show(UiObject *obj) {
    if(obj->wobj) {
        id<UiToplevelObject> window = (__bridge id<UiToplevelObject>)obj->wobj;
        
        if(![window getIsVisible]) {
            obj->ref++;
        }
        
        [window setVisible:YES];
    }
}

void ui_close(UiObject *obj) {
    // TODO: unref, window close, ...
    if(obj->wobj) {
        id<UiToplevelObject> window = (__bridge id<UiToplevelObject>)obj->wobj;
        [window setVisible:NO];
    }
}

/* ------------------- Job Control / Threadpool functions ------------------- */

void ui_job(UiObject *obj, ui_threadfunc tf, void *td, ui_callback f, void *fd) {
    UiThread *thread = [[UiThread alloc]init:obj jobfunc:tf jobdata:td];
    thread.finish_callback = f;
    thread.finish_userdata = fd;
    [thread start];
}

@implementation UiAppCallback

- (id) initWithCallback:(ui_threadfunc)func userdata:(void*)userdata {
    _callback = func;
    _userdata = userdata;
    return self;
}

- (void) callMainThread {
    [self performSelectorOnMainThread:@selector(mainThread:)
                                   withObject:nil
                                waitUntilDone:NO];
}

- (void) mainThread:(id)n {
    if(_callback) {
        _callback(_userdata);
    }
}

@end

void ui_call_mainthread(ui_threadfunc tf, void* td) {
    if(uic_mainthread_calls_is_buffered()) {
        uic_add_buffered_mainthread_call(tf, td);
        return;
    }
    
    UiAppCallback *cb = [[UiAppCallback alloc]initWithCallback:tf userdata:td];
    [cb callMainThread];
}
