#include "ubhello.h"

config main_config;

//functions

void yon_window_translate(GtkWidget *target){
    gtk_window_set_title(GTK_WINDOW(target),TITLE_LABEL);
}

void yon_title_info_translate(GtkWidget *title_label){
    char *title = TITLE_INFO_LABEL;
    gtk_label_set_text(GTK_LABEL(title_label),title);
    free(title);
}

void on_app_translate(GtkWidget *row){
    app_struct *cur_app = g_object_get_data(G_OBJECT(row),"app_struct");
    GKeyFile *file = g_key_file_new();
    g_key_file_load_from_file(file,cur_app->app->Desktop_path,G_KEY_FILE_NONE,NULL);
    char *locale_name = g_key_file_get_locale_string(file,"Desktop Entry","Name",NULL,NULL);
    gtk_label_set_text(GTK_LABEL(cur_app->AppLabel),locale_name);
    g_key_file_free(file);
    free(locale_name);
}

void on_translation_changed(GtkWidget *, main_window *widgets){
    const char *local = gtk_combo_box_get_active_id(GTK_COMBO_BOX(widgets->LanguageCombo));
    if (yon_char_is_empty(local)) return;
    yon_config_register(LANG_parameter,LANG_parameter_command,(char*)local);
    yon_translation_set_language(local,LocaleName);

    yon_update_translation();
}

void on_resource_activate(GtkWidget *, GtkWidget *row, main_window *widgets){
    resource_struct *cur_resource = g_object_get_data(G_OBJECT(row),"resource_struct");
    char *command = yon_char_unite("xdg-open ", cur_resource->link,NULL);
    switch(gtk_switch_get_active(GTK_SWITCH(widgets->WebkitSwitch))){
        case 0:
            yon_launch_app_with_arguments(command,NULL);
        break;
        case 1:
            yon_ubl_browser_window_open(cur_resource->link,TITLE_LABEL);
        break;
    }
    free(command);
}

resource_struct *yon_resource_struct_new(){
    resource_struct *resource_app = malloc(sizeof(resource_struct));
    memset(resource_app,0,sizeof(resource_struct));

    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_resource);
    resource_app->MainRow = yon_gtk_builder_get_widget(builder,"MainRow");
    resource_app->AppIcon = yon_gtk_builder_get_widget(builder,"AppIcon");
    resource_app->AppLabel = yon_gtk_builder_get_widget(builder,"AppLabel");

    g_signal_connect(G_OBJECT(resource_app->MainRow),"activate",G_CALLBACK(on_resource_activate),resource_app);
    g_object_set_data(G_OBJECT(resource_app->MainRow),"resource_struct",resource_app);

    return resource_app;
}

void on_quick_start_close(GtkWidget *, main_window *widgets){
    g_signal_handlers_disconnect_by_func(G_OBJECT(widgets->BackButton),G_CALLBACK(on_quick_start_close),widgets);
    GtkWidget *webkit = g_object_get_data(G_OBJECT(widgets->BackButton),"webkit");
    gtk_widget_hide(webkit);
    gtk_widget_hide(widgets->BackButton);
    gtk_widget_show(widgets->QuickStartList);
    webkit_web_view_load_html(WEBKIT_WEB_VIEW(webkit),"",NULL);
}

void on_quick_start_activate(GtkWidget *, GtkWidget *row, main_window *widgets){
    quick_start_struct *cur_app = g_object_get_data(G_OBJECT(row),"quick_start_struct");
    char *cur_locale = yon_char_new(setlocale(LC_ALL,NULL));
    char *locale_str = yon_char_divide_search(cur_locale,"_",-1);
    free(cur_locale);
    char *full_path = yon_char_unite(markdown_path,locale_str,"/",cur_app->file_path,NULL);
    int size = 0;
    config_str file_contents = yon_file_open(full_path, &size);
    if (!size||!file_contents) return;
    char *contents = yon_char_parsed_to_string(file_contents,size," ");
    yon_char_parsed_free(file_contents,size);
    
    GtkWidget *webkit = NULL;
    webkit = g_object_get_data(G_OBJECT(widgets->BackButton),"webkit");
    if (!webkit){
        webkit = webkit_web_view_new();
        gtk_overlay_add_overlay(GTK_OVERLAY(widgets->MainOverlay),webkit);
    }
    gtk_widget_show(webkit);
    gtk_widget_show(widgets->BackButton);
    g_object_set_data(G_OBJECT(widgets->BackButton),"webkit",webkit);
    g_signal_connect(G_OBJECT(widgets->BackButton),"clicked",G_CALLBACK(on_quick_start_close),widgets);
    webkit_web_view_load_html(WEBKIT_WEB_VIEW(webkit),contents,g_filename_to_uri(base_uri,NULL,NULL));
    while(gtk_events_pending()) gtk_main_iteration();
    gtk_widget_hide(widgets->QuickStartList);
    free(contents);
}

quick_start_struct *yon_quick_start_struct_new(){
    quick_start_struct *resource_app = malloc(sizeof(quick_start_struct));
    memset(resource_app,0,sizeof(quick_start_struct));

    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_quick_start);
    resource_app->MainRow = yon_gtk_builder_get_widget(builder,"MainRow");
    resource_app->AppIcon = yon_gtk_builder_get_widget(builder,"AppIcon");
    resource_app->AppLabel = yon_gtk_builder_get_widget(builder,"AppLabel");

    g_object_set_data(G_OBJECT(resource_app->MainRow),"quick_start_struct",resource_app);

    return resource_app;
}

void on_app_activate(GtkWidget *, GtkWidget *row, main_window *widgets){
    app_struct *cur_app = g_object_get_data(G_OBJECT(row),"app_struct");
    int socket_support = cur_app->app->Pluggable;
    char *socket_string = NULL;
    if (socket_support){
        GtkWidget *socket = gtk_socket_new();
        gtk_overlay_add_overlay(GTK_OVERLAY(widgets->MainOverlay),socket);
        gtk_widget_show(socket);
        socket_string = yon_char_unite("--socket-id ", yon_char_from_long((long)gtk_socket_get_id(GTK_SOCKET(socket))),NULL);
        g_signal_connect(G_OBJECT(socket),"plug_added",G_CALLBACK(on_plug_connected),widgets);
        g_signal_connect(G_OBJECT(socket),"destroy",G_CALLBACK(on_plug_disconnected),widgets);
    }
    char *command = yon_char_unite("setsid ", cur_app->app->Exec, " ", socket_string, NULL);
    
    yon_launch_app_with_arguments(command,NULL);
}

app_struct *yon_app_struct_new(){
    app_struct *cur_app = malloc(sizeof(app_struct));
    memset(cur_app,0,sizeof(app_struct));

    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_app);
    cur_app->MainRow = yon_gtk_builder_get_widget(builder,"MainRow");
    cur_app->AppIcon = yon_gtk_builder_get_widget(builder,"AppIcon");
    cur_app->AppLabel = yon_gtk_builder_get_widget(builder,"AppLabel");

    g_signal_connect(G_OBJECT(cur_app->MainRow),"activate",G_CALLBACK(on_app_activate),cur_app);
    g_object_set_data(G_OBJECT(cur_app->MainRow),"app_struct",cur_app);

    return cur_app;
}

gboolean on_ubhello_reopen(GtkWidget *, guint state, main_window *){
    switch(state){
        case 0:
            yon_window_config_add_instant_parameter("firststart","window","no",YON_TYPE_STRING);
        break;
        case 1:
            yon_window_config_add_instant_parameter("firststart","window","yes",YON_TYPE_STRING);
        break;
    }
    return 0;
}

void yon_language_update(GtkWidget *target){
    main_window *widgets = g_object_get_data(G_OBJECT(target),"widgets");
    g_signal_handlers_block_by_func(G_OBJECT(target),G_CALLBACK(on_translation_changed),widgets);
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(target));
    int codes_size=0;
    int size = 0;
    config_str codes_list = yon_locale_get_all_codes(&codes_size);
    config_str codes = yon_file_list_dirs(languages_search_path,&size);
    textdomain(LOCALES_DOMAIN_NAME);
    for (int i=0;i<size;i++){
        char *temp = yon_char_unite(codes[i],"_",NULL);
        int active = yon_char_parsed_strstr(codes_list,codes_size,temp);
        free(temp);
        if (active==-1) continue;
        char *name = yon_locale_get_parameter(codes_list[active],YON_LOCALE_LANGUAGE);
        char *code = yon_locale_get_parameter(codes_list[active],YON_LOCALE_CODE);
        if (!yon_char_is_empty(name)){
            gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(target),code,_(name));
        }
    }
    textdomain(LocaleName);
    char *current_lang = config(LANG_parameter);
    if (!yon_char_is_empty(current_lang)&&g_utf8_get_char_validated(current_lang,strlen(current_lang))){
        gtk_combo_box_set_active_id(GTK_COMBO_BOX(widgets->LanguageCombo),current_lang);
    }
    g_signal_handlers_unblock_by_func(G_OBJECT(target),G_CALLBACK(on_translation_changed),widgets);
}

gboolean yon_interface_update(main_window *){

    return G_SOURCE_REMOVE;
}
// standard functions

/**yon_main_window_complete(main_window *widgets) 
 * [EN] 
 *  
 * [RU] 
 * Функция настройки основного окна приложения. [widgets] - структура со стандартным интерфейсом. 
*/ 
main_window *yon_main_window_complete(main_window *widgets){ 
    __attribute__((unused)) char *locale = setlocale(LC_ALL, "en_US.UTF-8");
    widgets = yon_remalloc(widgets,sizeof(main_window)); 
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path); 
    GSList *list = gtk_builder_get_objects(builder);
    yon_translation_init(list);
    yon_gtk_widget_set_translation(widgets->HeadLabel);
    yon_gtk_widget_set_translation(widgets->StatusLabel);
    yon_gtk_widget_set_translation(widgets->HeadInfoLabel);
    yon_gtk_widget_set_translation(widgets->HeadTitleLabel);
    yon_translation_set_translation_func(widgets->HeadInfoLabel,yon_title_info_translate);
    yon_translation_set_translation_func(widgets->Window,yon_window_translate);
    gtk_box_pack_start(GTK_BOX(widgets->InterfaceBox),yon_gtk_builder_get_widget(builder,"BoxMain"),1,1,0); 
    // Custom widgets configuration 
    {
        widgets->QuickStartList = yon_gtk_builder_get_widget(builder,"QuickStartList");
        widgets->ManagementFlow = yon_gtk_builder_get_widget(builder,"ManagementFlow");
        widgets->WebkitSwitch = yon_gtk_builder_get_widget(builder,"WebkitSwitch");
        widgets->ResourcesFlow =  yon_gtk_builder_get_widget(builder,"ResourcesFlow");
        widgets->LanguageCombo = yon_gtk_builder_get_widget(builder,"LanguageCombo");
        widgets->StartupSwitch = yon_gtk_builder_get_widget(builder,"StartupSwitch");
        widgets->MainOverlay = yon_gtk_builder_get_widget(builder,"MainOverlay");
        widgets->BackButton = yon_gtk_builder_get_widget(builder,"BackButton");
        gtk_header_bar_pack_start(GTK_HEADER_BAR(gtk_window_get_titlebar(GTK_WINDOW(widgets->Window))),widgets->BackButton);

        g_signal_connect(G_OBJECT(widgets->QuickStartList),"row-activated", G_CALLBACK(on_quick_start_activate),widgets);
        g_signal_connect(G_OBJECT(widgets->ManagementFlow),"child-activated", G_CALLBACK(on_app_activate),widgets);
        g_signal_connect(G_OBJECT(widgets->ResourcesFlow),"child-activated", G_CALLBACK(on_resource_activate),widgets);
        g_signal_connect(G_OBJECT(widgets->LanguageCombo),"changed", G_CALLBACK(on_translation_changed),widgets);
        g_object_set_data(G_OBJECT(widgets->LanguageCombo),"widgets",widgets);
        gtk_widget_set_size_request(widgets->Window,1024,768);
    }
    yon_translation_set_translation_func(widgets->LanguageCombo,yon_language_update);
    yon_apps_init();
    textdomain (LocaleName);
    {
        g_signal_connect(G_OBJECT(widgets->StartupSwitch),"state-set",G_CALLBACK(on_ubhello_reopen),widgets);
        int size = 0;
        config_str apps_list = yon_resource_open_file(apps_path,&size);
        for (int i=1;i<size;i++){
            yon_char_remove_last_symbol(apps_list[i],"\n");
            apps *cur_application = yon_apps_find(apps_list[i]);
            if (!cur_application) continue;
            app_struct *cur_app = yon_app_struct_new();
            cur_app->app = cur_application;

            gtk_widget_show(cur_app->MainRow);
            gtk_flow_box_insert(GTK_FLOW_BOX(widgets->ManagementFlow),cur_app->MainRow,-1);
            gtk_label_set_text(GTK_LABEL(cur_app->AppLabel),cur_application->Name);
            gtk_image_set_from_icon_name(GTK_IMAGE(cur_app->AppIcon),cur_application->Icon,GTK_ICON_SIZE_BUTTON);
            gtk_image_set_pixel_size(GTK_IMAGE(cur_app->AppIcon),48);
            yon_translation_set_translation_func(cur_app->MainRow,on_app_translate);

        }
        yon_char_parsed_free(apps_list,size);
    }
    {
        int size = 0;
        config_str apps_list = yon_resource_open_file(docs_path,&size);
        for (int i=1;i<size;i++){
            yon_char_remove_last_symbol(apps_list[i],"\n");
            quick_start_struct *cur_app = yon_quick_start_struct_new();

            cur_app->file_path = yon_char_get_element(apps_list[i],1,";");
            gtk_widget_show(cur_app->MainRow);
            gtk_list_box_insert(GTK_LIST_BOX(widgets->QuickStartList),cur_app->MainRow,-1);
            gtk_label_set_text(GTK_LABEL(cur_app->AppLabel),_(yon_char_get_element(apps_list[i],0,";")));
            yon_gtk_widget_set_translation(cur_app->AppLabel);
        }
        yon_char_parsed_free(apps_list,size);
    }
    {
        int size = 0;
        config_str apps_list = yon_resource_open_file(links_path,&size);
        for (int i=1;i<size;i++){
            yon_char_remove_last_symbol(apps_list[i],"\n");

            resource_struct *cur_app = yon_resource_struct_new();

            cur_app->link = yon_char_get_element(apps_list[i],1,";");
            gtk_widget_show(cur_app->MainRow);
            gtk_label_set_text(GTK_LABEL(cur_app->AppLabel),_(yon_char_get_element(apps_list[i],0,";")));
            gtk_flow_box_insert(GTK_FLOW_BOX(widgets->ResourcesFlow),cur_app->MainRow,-1);
            yon_gtk_widget_set_translation(cur_app->AppLabel);
        }
        yon_char_parsed_free(apps_list,size);
    }

    yon_load_proceed();

    yon_locale_init();
    gtk_widget_hide(widgets->Window);
    yon_interface_update(widgets);
    yon_language_update(widgets->LanguageCombo);
    char *current_lang = config(LANG_parameter);
    if (!yon_char_is_empty(current_lang)&&g_utf8_get_char_validated(current_lang,strlen(current_lang))){
        gtk_combo_box_set_active_id(GTK_COMBO_BOX(widgets->LanguageCombo),current_lang);
        on_translation_changed(NULL,widgets);
    }
    // on_config_local_load(NULL,widgets);
    return widgets;
}

int main(int argc, char *argv[]){ 
    setlocale(LC_ALL, "en_US.UTF-8");
    textdomain (LocaleName);
    bind_textdomain_codeset(LocaleName,"UTF-8");
    yon_ubl_connect_config((_template_config*)&main_config); 
    yon_ubl_window_init(TITLE_LABEL,TITLE_INFO_LABEL,LocaleName,CssPath,LocaleName,version_application,WIKI_LINK);
	config_str unfound = NULL;
	int size=0;
    opterr=0;
	yon_ubl_setup_arguments(argc,argv,&unfound,&size,ADDITIONAL_ARGS);
    // opterr=1;
    if (size) {
        int option_index = 0;
        struct option long_options[] = {
            {"firststart", 0, 0, 'F'},
            {NULL, 0, NULL, 0}
        };
        optind = 1;
        for (int i = 0; i < size; i++) {
            int argument = getopt_long(argc, argv, "F", long_options, &option_index);
            switch (argument) {
                case 'F':
                    main_config.firststart = 1;
                    break;
                default:
                    break;
            }
        }
    }

    gtk_init(&argc,&argv);
    template_main_window *widgets = yon_ubl_window_setup(); 
    
    GList *list = gtk_container_get_children(GTK_CONTAINER(gtk_window_get_titlebar(GTK_WINDOW(widgets->Window))));
    GList *iter;
    for (iter=list;iter;iter=iter->next){
        if (GTK_IS_BOX(iter->data)){
            GList *chlist = gtk_container_get_children(GTK_CONTAINER(iter->data));
            if (chlist->next){
                gtk_widget_hide(GTK_WIDGET(chlist->data));
            } else {
                gtk_widget_hide(GTK_WIDGET(iter->data));
            }
        }
    }
    
    //turn off if custom presented
    main_config.launch_arguments=yon_char_parsed_copy(argv,argc);
    main_config.launch_size=argc;
    widgets = (template_main_window*)yon_main_window_complete((main_window*)widgets);
    char *path = yon_char_unite(yon_ubl_user_get_home_directory(),"/.config/",LocaleName,"/",LocaleName,".conf",NULL);
    yon_window_config_load(path);
    if (main_config.firststart){
        char *firststart = NULL;
        yon_window_config_get_parameter("window","firststart",&firststart,YON_TYPE_STRING);
        if (!yon_char_is_empty(firststart)&&strcmp(firststart,"yes")){
            exit(10);
        } else if (yon_char_is_empty(firststart)){
            firststart = config(FIRSTSTART_parameter);
            if (yon_char_is_empty(firststart)||strcmp(firststart,"yes")){
                exit(10);
            }
        }

    } else {
        char *firststart = config(FIRSTSTART_parameter);
        if (yon_char_is_empty(firststart)){
            firststart = "no";
        }
        yon_window_config_add_instant_parameter("firststart","window",firststart,YON_TYPE_STRING);
    }

        char *firststart = NULL;
        yon_window_config_get_parameter("window","firststart",&firststart,YON_TYPE_STRING);
        if (!yon_char_is_empty(firststart)&&!strcmp(firststart,"yes")){
            gtk_switch_set_active(GTK_SWITCH(((main_window*)widgets)->StartupSwitch),1);
        } else {
            gtk_switch_set_active(GTK_SWITCH(((main_window*)widgets)->StartupSwitch),0);
        }
    gtk_widget_show(widgets->Window);
    list = gtk_container_get_children(GTK_CONTAINER(widgets->StatusBox));
    iter = NULL;
    for (iter=list;iter;iter=iter->next){
        gtk_widget_destroy(GTK_WIDGET(iter->data));
    }
    gtk_style_context_remove_class(gtk_widget_get_style_context(widgets->StatusBox),"boxInfoMessOK");
    gtk_style_context_remove_class(gtk_widget_get_style_context(widgets->StatusBox),"boxInfoMessError");
    gtk_main();
    return 0;
}