#include "ubinstall-gtk.h"

void yon_language_update(main_window *widgets){
    gtk_list_store_clear(widgets->LanguageList);
    {
        char *config_locale = config(locale_parameter);
        char *config_languages = config(lang_parameter);
        if (yon_char_is_empty(config_locale)||yon_config_check_ignore(locale_parameter)){
            gtk_switch_set_active(GTK_SWITCH(widgets->LocaleDefaultSwitch),1);
            GtkTreeIter iter;
                char *cur_lang = g_hash_table_lookup(main_config.languages,"en_US.UTF-8");
                if (!yon_char_is_empty(cur_lang)){
                    int parsed_size;
                    config_str parsed = yon_char_parse(cur_lang,&parsed_size,"|");
                    gtk_list_store_append(widgets->LanguageList,&iter);
                    gtk_list_store_set(widgets->LanguageList,&iter,0,1,1,parsed[1],2,parsed[2],3,parsed[0],-1);
                }
        } else {
            gtk_switch_set_active(GTK_SWITCH(widgets->LocaleDefaultSwitch),0);
            int parsed_param_size;
            config_str parsed_param = yon_char_parse(config_locale,&parsed_param_size,",");
            GtkTreeIter iter;
            for (int i=0;i<parsed_param_size;i++){
                char *cur_lang = g_hash_table_lookup(main_config.languages,parsed_param[i]);
                if (!yon_char_is_empty(cur_lang)){
                    int parsed_size;
                    config_str parsed = yon_char_parse(cur_lang,&parsed_size,"|");
                    gtk_list_store_append(widgets->LanguageList,&iter);
                    gtk_list_store_set(widgets->LanguageList,&iter,1,parsed[1],2,parsed[2],3,parsed[0],-1);
                    if (!yon_char_is_empty(config_languages)){
                        if (!strcmp(config_languages,parsed[0])){
                            gtk_list_store_set(widgets->LanguageList,&iter,0,1,-1);
                        } 
                    }
                    yon_char_parsed_free(parsed,parsed_size);
                }
            }
            if (!config_languages){
                if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(widgets->LanguageList),&iter)){
                    gtk_list_store_set(widgets->LanguageList,&iter,0,1,-1);
                }
            }
        }
    }

}


void on_locale_toggle(GtkCellRenderer *, gchar *path,language_window *window){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(window->LanguagesList);
    gtk_tree_model_get_iter_from_string(model,&iter,path);
    gboolean is_active;
    char *target;
    gtk_tree_model_get(model,&iter,0,&is_active,1,&target,-1);
    gtk_list_store_set(GTK_LIST_STORE(model),&iter,0,!is_active,-1);

    char *locales = (char*)gtk_entry_get_text(GTK_ENTRY(window->ManualEntry));
    if (!is_active){
        if (!yon_char_check_element(locales,target,",")){
            char *temp = yon_char_append_element(locales,target,",");
            gtk_entry_set_text(GTK_ENTRY(window->ManualEntry),temp);
            free(temp);
        }
    } else {
        char *temp = yon_char_remove_element(locales,target,",");
        gtk_entry_set_text(GTK_ENTRY(window->ManualEntry),temp);
        if (!yon_char_is_empty(temp)) free(temp);
    }
}

void on_locale_accept(GtkWidget *self, language_window *window){
    main_window *widgets = g_object_get_data(G_OBJECT(window->Window),"widgets");

    char *final = (char*)gtk_entry_get_text(GTK_ENTRY(window->ManualEntry));
    if (yon_char_is_empty(final)) {
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),yon_char_get_localised_from_lib(NOTHING_CHOSEN_LABEL),5,BACKGROUND_IMAGE_FAIL_TYPE);
        return;
    }
    GtkTreeIter iter;
    char *sys_locale = NULL;
    for_iter(widgets->LanguageList,&iter){
        char *target;
        int status;
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->LanguageList),&iter,0,&status,3,&target,-1);
        if (status){
            sys_locale = target;
        }
    }
    gtk_list_store_clear(widgets->LanguageList);
    int size;
    config_str parsed = yon_char_parse(final,&size,",");
    for (int i=0;i<size;i++){
        char *locale_str = g_hash_table_lookup(main_config.languages,parsed[i]);
        if (yon_char_is_empty(locale_str)) continue;
        int parameter_size;
        config_str parameter_parsed = yon_char_parse(locale_str,&parameter_size,"|");
        gtk_list_store_append(widgets->LanguageList,&iter);
        gtk_list_store_set(widgets->LanguageList,&iter,1,parameter_parsed[1],2,parameter_parsed[2],3,parameter_parsed[0],-1);
        if (!yon_char_is_empty(sys_locale)&&!strcmp(parameter_parsed[0],sys_locale)){
            gtk_list_store_set(widgets->LanguageList,&iter,0,1,-1);
        }
    }
    on_subwindow_close(self);
}

gboolean yon_locale_window_set_locales(struct locales_struct *data){
    GtkTreeIter iter;
    gtk_list_store_append(GTK_LIST_STORE(data->list),&iter);
    gtk_list_store_set(GTK_LIST_STORE(data->list),&iter,1,data->locale,2,data->lang,3,data->territory,0,data->chosen,-1);
    if(!yon_char_is_empty(data->lang)) free(data->lang);
    if(!yon_char_is_empty(data->locale)) free(data->locale);
    if(!yon_char_is_empty(data->territory)) free(data->territory);
    if(data) free(data);
    return G_SOURCE_REMOVE;
}

gboolean yon_locale_window_unlock(GtkWidget *spinner){
    gtk_widget_hide(spinner);
    return G_SOURCE_REMOVE;
}

gboolean yon_locale_window_load(language_window *window){
    main_window *widgets = g_object_get_data(G_OBJECT(window->Window),"widgets");
        char *config_languages = NULL;
    GtkTreeIter iter;
    for_iter (widgets->LanguageList,&iter){
        char *code;
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->LanguageList),&iter,3,&code,-1);
        char *temp = yon_char_append_element(config_languages,code,",");
        if (!yon_char_is_empty(config_languages)) free(config_languages);
        config_languages = temp;
    }
    if (!yon_char_is_empty(config_languages))
        gtk_entry_set_text(GTK_ENTRY(window->ManualEntry),config_languages);
    for_iter (window->LanguagesList,&iter){
        char *code;
        gtk_tree_model_get(GTK_TREE_MODEL(window->LanguagesList),&iter,1,&code,-1);
        if (yon_char_check_element(config_languages,code,",")){
            gtk_list_store_set(window->LanguagesList,&iter,0,1,-1);
        }
    }
    yon_locale_window_unlock(window->LoadingSpinner);
    return G_SOURCE_REMOVE;
}

void *yon_locales_load_func(language_window *window){
    int config_parsed_size;
    config_str config_parsed = yon_char_parse(window->languages,&config_parsed_size,",");

    int size;
    config_str languages = yon_config_load(languages_command,&size);
    for (int i=0;i<size;i++){
        struct locales_struct *data_struct = malloc(sizeof(struct locales_struct));
        data_struct->list=window->LanguagesList;
        yon_char_remove_last_symbol(languages[i],'\n');
        int parsed_size;
        config_str parsed = yon_char_parse(languages[i],&parsed_size,"|");
        data_struct->locale = yon_char_new(parsed[0]);
        data_struct->lang = yon_char_new(parsed[1]);
        data_struct->territory = yon_char_new(parsed[2]);

        if (config_parsed_size&&yon_char_parsed_check_exist(config_parsed,config_parsed_size,parsed[0])>-1){
            data_struct->chosen=1;
        } else {
            data_struct->chosen=0;
        }
        g_idle_add((GSourceFunc)yon_locale_window_set_locales,data_struct);
        yon_char_parsed_free(parsed,parsed_size);
    }
    g_idle_add((GSourceFunc)yon_locale_window_load,window);
    g_idle_add((GSourceFunc)yon_locale_window_unlock,window->LoadingSpinner);
    yon_char_parsed_free(config_parsed,config_parsed_size);
    g_thread_exit(NULL);
}

language_window *yon_language_window_new(char *chosen_languages){
    language_window *window = malloc(sizeof(language_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_locales_path);
    window->Window = yon_gtk_builder_get_widget(builder,"Window");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->LanguagesTree = yon_gtk_builder_get_widget(builder,"LanguagesTree");
    window->CancelButton = yon_gtk_builder_get_widget(builder,"CancelButton");
    window->AcceptButton = yon_gtk_builder_get_widget(builder,"AcceptButton");
    window->ManualEntry = yon_gtk_builder_get_widget(builder,"ManualEntry");
    window->LoadingOverlay = yon_gtk_builder_get_widget(builder,"LoadingOverlay");
    window->LoadingSpinner = yon_gtk_builder_get_widget(builder,"LoadingSpinner");
    window->ToggleCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"ToggleCell"));
    window->LanguagesList = GTK_LIST_STORE(gtk_builder_get_object(builder,"LanguagesList"));
    window->languages = yon_char_new(chosen_languages);

    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
    g_signal_connect(G_OBJECT(window->AcceptButton),"clicked",G_CALLBACK(on_locale_accept),window);
    g_signal_connect(G_OBJECT(window->ToggleCell),"toggled",G_CALLBACK(on_locale_toggle),window);
    yon_gtk_tree_view_minimal_fixed_size_set_full(GTK_TREE_VIEW(window->LanguagesTree));

    if (!yon_char_is_empty(window->languages)){
        gtk_entry_set_text(GTK_ENTRY(window->ManualEntry),chosen_languages);
    }

    gtk_overlay_add_overlay(GTK_OVERLAY(window->LoadingOverlay),window->LoadingSpinner);
    g_thread_new("locales-thread",(GThreadFunc)yon_locales_load_func,window);

    return window;
}

void on_language_open(GtkWidget *, main_window *widgets){
    GtkTreeIter iter;
    char *languages = NULL;
    for_iter(GTK_TREE_MODEL(widgets->LanguageList),&iter){
        char *target;
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->LanguageList),&iter,3,&target,-1);
        char *temp = yon_char_append_element(languages,target,",");
        if (!yon_char_is_empty(languages)) free(languages);
        languages = temp;
    }
    language_window *window = yon_language_window_new(languages);

    g_object_set_data(G_OBJECT(window->Window),"widgets",widgets);

    yon_gtk_window_setup(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->MainWindow),ADD_LANGUAGE_TITLE_LABEL,icon_path,"LocalesWindow");
    

    gtk_widget_show(window->Window);
    
}

void on_language_remove(GtkWidget *, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->LocaleTree)),&model,&iter)){
        gtk_list_store_remove(widgets->LanguageList,&iter);
    }
}


void on_language_default_toggled(GtkWidget *, int status, main_window *widgets){
    gtk_widget_set_sensitive(widgets->LocaleTree,!status);
    gtk_widget_set_sensitive(widgets->LocaleAddButton,!status);
    GtkTreeModel *model;
    GtkTreeIter iter;
    if (!status&&gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->LocaleTree)),&model,&iter)){
        gtk_widget_set_sensitive(widgets->LocaleRemoveButton,1);
    } else {
        gtk_widget_set_sensitive(widgets->LocaleRemoveButton,0);
    }
}

void on_locale_selected(GtkTreeView *,main_window *widgets){
    GtkTreeModel *model = NULL;
    GtkTreeIter iter;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->LocaleTree)),&model,&iter)){
        gtk_widget_set_sensitive(widgets->LocaleRemoveButton,1);
    } else {
        gtk_widget_set_sensitive(widgets->LocaleRemoveButton,0);
    }
}

void on_locale_toggled(GtkCellRenderer *, gchar *path, main_window *widgets){
    GtkTreeIter fiter;
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->LanguageList);
    gtk_tree_model_get_iter_from_string(model,&fiter,path);
    for_iter(model,&iter){
        gtk_list_store_set(GTK_LIST_STORE(model),&iter,0,0,-1);

    }
    char *target;
    gtk_tree_model_get(model,&fiter,3,&target,-1);
    gtk_list_store_set(GTK_LIST_STORE(model),&fiter,0,1,-1);
}

int yon_language_save(main_window *widgets){
    int status = gtk_switch_get_active(GTK_SWITCH(widgets->LocaleDefaultSwitch));
    if (!status){
        GtkTreeModel *model = GTK_TREE_MODEL(widgets->LanguageList);
        GtkTreeIter iter;
        char *locales = NULL;
        for_iter(model,&iter){
            int status;
            char *target;

            gtk_tree_model_get(model,&iter,0,&status,3,&target,-1);
            char *temp = yon_char_append_element(locales?locales:"",target,",");
            if (!yon_char_is_empty(locales)) free(locales);
            locales = temp;
            if (status){
                yon_config_register(lang_parameter,lang_parameter_command,target);
            }
        }
        if (!yon_char_is_empty(locales)){
            yon_config_register(locale_parameter,locale_parameter_command,locales);
        }
    } else {
        yon_config_remove_by_key(lang_parameter);
        yon_config_remove_by_key(locale_parameter);
    }
    if (!main_config.configure_mode){
        yon_debug_output("%s\n",yon_config_save_args_simple(main_config.config_load_path,lang_parameter,locale_parameter,NULL));
    }

    return 1;
}

void yon_language_init(main_window *widgets){
    if (!main_config.configure_mode){
        yon_config_update_by_args(main_config.config_load_path, lang_parameter, locale_parameter,NULL);
    }
    yon_language_update(widgets);
}
