#include "ubinstall-gtk.h"

void on_locale_changed(GtkWidget *,main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->LanguagesTree)),&model,&iter)) return;
    // {
    //     GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(widgets->InstallerLanguageList),&iter);
    //     gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(widgets->LanguagesTree),path,0,0,0,0);
    //     gtk_tree_path_free(path);
    // }
    gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(widgets->InstallerCountryFilter));
    char *config_code = config(installer_locale_parameter);
    if (yon_char_is_empty(config_code)){
        config_code = setlocale(LC_ALL,NULL);
    }
    GtkTreeIter itar;
    for_iter(widgets->InstallerCountryFilter,&iter){
        gtk_tree_model_filter_convert_iter_to_child_iter(GTK_TREE_MODEL_FILTER(widgets->InstallerCountryFilter),&itar,&iter);
        char *target;
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->InstallerCountryList),&itar,2,&target,-1);
        if (!strcmp(config_code,target)){
            gtk_tree_model_filter_convert_child_iter_to_iter(GTK_TREE_MODEL_FILTER(widgets->InstallerCountryFilter),&iter,&itar);
            gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->CountryLanguagesTree)),&iter);
                GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(widgets->InstallerCountryFilter),&iter);
                gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(widgets->CountryLanguagesTree),path,0,0,0,0);
                gtk_tree_path_free(path);
            break;
        }
    }
    
}

void on_installer_language_changed(GtkWidget *self,GtkTreePath*,GtkTreeViewColumn*, main_window *widgets){
    char *window_language;
    GtkTreeIter iter;
    GtkTreeModel *model;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->CountryLanguagesTree)),&model,&iter)) return;
    gtk_tree_model_get(model,&iter,2,&window_language,-1);
    if (!yon_char_is_empty(window_language)){
        char *prev_lang = config(installer_locale_parameter);
        if (!yon_char_is_empty(prev_lang)&&!strcmp(prev_lang,window_language)) return;
        yon_config_register(installer_locale_parameter,installer_locale_parameter_command,(char*)window_language);
    }
    char *active_lang_id = gtk_tree_model_get_string_from_iter(model,&iter);
    int size;
    config_str parameters = yon_config_get_save_parameters_by_key(&size,installer_locale_parameter,NULL);
    char *command_parameters = yon_char_parsed_to_string(parameters,size," ");
    char *command = yon_char_unite(ubconfig_dull_command,"--target system ",command_parameters,NULL);
    if (!system(command)){};
    yon_main_window_update_locale(widgets);
    g_signal_handlers_block_by_func(G_OBJECT(self),G_CALLBACK(on_locale_changed),widgets);
    model = GTK_TREE_MODEL(widgets->InstallerLanguageList);
    gtk_tree_model_get_iter_from_string(model,&iter,active_lang_id);
    g_signal_handlers_unblock_by_func(G_OBJECT(self),G_CALLBACK(on_locale_changed),widgets);

}

void yon_startup_language_init(){
    char *source = yon_config_get_type_path(main_config.load_mode);
    if (!source){
        source = main_config.custom_load_path;
    }
    char *command =yon_config_parameter_prepare_command(get_localisation_command,source,NULL,NULL);
    int size;
    config_str parsed = yon_config_load(command,&size);
    {
        if (size>0&&!yon_char_is_empty(parsed[0])&&strcmp(parsed[0],"(null)\n")){
            yon_char_remove_last_symbol(parsed[0],'\n');
            if (strstr(parsed[0],"="))
            free(yon_char_divide_search(parsed[0],"=",-1));
            yon_config_register(installer_locale_parameter,installer_locale_parameter_command,parsed[0]);
        }
        if (size>1&&!yon_char_is_empty(parsed[1])&&strcmp(parsed[1],"(null)\n")){
            yon_char_remove_last_symbol(parsed[1],'\n');
            if (strstr(parsed[1],"="))
            free(yon_char_divide_search(parsed[1],"=",-1));
            yon_char_remove_brackets(parsed[1]);
            yon_config_register(installer_locale_parameter,installer_locale_parameter_command,parsed[1]);
        }
        if (size>2&&!yon_char_is_empty(parsed[2])&&strcmp(parsed[2],"(null)\n")){
            yon_char_remove_last_symbol(parsed[2],'\n');
            if (strstr(parsed[2],"="))
            free(yon_char_divide_search(parsed[2],"=",-1));
            yon_char_remove_brackets(parsed[2]);
            yon_config_register(installer_locale_parameter,installer_locale_parameter_command,parsed[2]);
        } else {
            yon_config_register(installer_locale_parameter,installer_locale_parameter_command,setlocale(LC_ALL,""));

        }
    }
}

void yon_main_window_update_locale(main_window *widgets){
    char *locale = yon_char_new(config(installer_locale_parameter));
    if (yon_char_is_empty((char *)locale)){
        char *sys_locale = config(lang_parameter);

        if (!yon_char_is_empty(sys_locale)){
            locale = sys_locale;
        } else {
            char *lang = config("LANG");
            if (!yon_char_is_empty(lang)){
                locale = lang;
            }
        }
        if (yon_char_is_empty(locale)){
            locale = setlocale(LC_ALL,NULL);
        }
    }
        setlocale(LC_ALL,(char *)locale);
        yon_config_register(installer_locale_parameter,installer_locale_parameter_command,(char*)locale);

    // gtk_widget_destroy(widgets->MainWindow);
    textdomain(LocaleName);
    g_setenv("LANGUAGE",(char *)locale,1);
    yon_installer_update_translation(widgets);
    // yon_main_window_create(widgets);
    char *path = yon_char_unite(yon_ubl_user_get_home_directory(),"/.config/",LocaleName,"/",LocaleName,".conf",NULL);
    yon_window_config_setup(GTK_WINDOW(widgets->MainWindow));
    yon_window_config_load(path);
    
}

typedef struct{
    char *locale_name;
    char *code;
    char *localised_name;
    char *code_full;
} locale_struct;

gboolean on_languages_search_func(GtkTreeModel *model, gint ,const char *key, GtkTreeIter *iter, main_window *){
    char *target;
    char *loc_target;
    gtk_tree_model_get(model, iter, 1,&target, 4, &loc_target,-1);
    char *string_utf = g_utf8_casefold(key,-1);
    char *target_utf = g_utf8_casefold(target,-1);
    char *loc_target_utf = g_utf8_casefold(loc_target,-1);

    char *string_normalized = g_utf8_strdown(g_utf8_normalize(string_utf,-1,G_NORMALIZE_DEFAULT),-1);
    char *target_normalized = g_utf8_strdown(g_utf8_normalize(target_utf,-1,G_NORMALIZE_DEFAULT),-1);
    char *loc_target_normalized = g_utf8_strdown(g_utf8_normalize(loc_target_utf,-1,G_NORMALIZE_DEFAULT),-1);

    return !(g_str_has_prefix(target_normalized,string_normalized) || g_str_has_prefix(loc_target_normalized,string_normalized));
}

void yon_set_locales_list(main_window *widgets){
    gtk_list_store_clear(widgets->InstallerLanguageList);
    gtk_list_store_clear(widgets->InstallerCountryList);

    char *config_code = yon_char_new(config(installer_locale_parameter));
    int size;
    config_str locales = yon_locale_get_all_codes(&size);
    qsort(locales,size,sizeof(char*),(__compar_fn_t)yon_char_parsed_compare);
    GtkTreeIter iter,itar;
    GHashTable *added = g_hash_table_new(g_str_hash,g_str_equal);
    textdomain(LOCALES_DOMAIN_NAME);
    for (int i=0;i<size;i++){
        char *lang_ab = yon_locale_get_parameter(locales[i],YON_LOCALE_LANG_AB);
        char *code = yon_locale_get_parameter(locales[i],YON_LOCALE_CODE);
        char *language = yon_locale_get_parameter(locales[i],YON_LOCALE_LANGUAGE);
        char *lang_name = yon_locale_get_parameter(locales[i],YON_LOCALE_LANG_NAME);
        char *territory = yon_locale_get_parameter(locales[i],YON_LOCALE_TERRITORY);
        char *title = yon_locale_get_parameter(locales[i],YON_LOCALE_TITLE);
        if (yon_char_is_empty(lang_ab)||
            yon_char_is_empty(language)||
            yon_char_is_empty(lang_name)||
            yon_char_is_empty(territory)||
            yon_char_is_empty(title)) continue;

        char *country = yon_char_unite(language,", ",territory,NULL);
        if (!g_hash_table_contains(added,lang_ab)){
            g_hash_table_add(added,yon_char_new(lang_ab));
            gtk_list_store_append(widgets->InstallerLanguageList,&iter);
            gtk_list_store_set(widgets->InstallerLanguageList,&iter,
            0,lang_ab,
            1,_(language),
            2,lang_name,
            3,locales[i],
            4,language,
            -1);
        }

        gtk_list_store_append(widgets->InstallerCountryList,&itar);
        gtk_list_store_set(widgets->InstallerCountryList,&itar,
        0,lang_ab,
        1,_(country),
        2,code,
        3,_(title),
        -1);
    }
    for_iter (GTK_TREE_MODEL(widgets->InstallerLanguageList), &iter){
        char *compare_target;
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->InstallerLanguageList),&iter, 3, &compare_target, -1);
        if (!yon_char_is_empty(config_code)){
            char *temp = strstr(config_code,".");
            if (temp) temp[0]='\0';
            char *compare_lang_ab =yon_locale_get_parameter(compare_target,YON_LOCALE_LANG_AB);
            temp = strstr(config_code,"_");
            if (temp) temp[0]='\0';
            if (!strcmp(config_code,compare_lang_ab)){
                gtk_widget_realize(widgets->LanguagesTree);
                GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(widgets->InstallerLanguageList),&iter);
                gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(widgets->LanguagesTree),path,0,0,0,0);
                gtk_tree_path_free(path);
                gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->LanguagesTree)),&iter);
                on_locale_changed(NULL,widgets);
            }
        }
    }
    textdomain(LocaleName);
}

gboolean on_country_filter(GtkTreeModel *self, GtkTreeIter *iter, main_window *widgets){
    GtkTreeIter itar;
    GtkTreeModel *model;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->LanguagesTree)),&model,&itar)) return 0;
    char *cur_code,*country;
    gtk_tree_model_get(self,iter,0,&cur_code,1,&country,-1);
    if (yon_char_is_empty(cur_code)) return 0;

    char *code;
    gtk_tree_model_get(model,&itar,0,&code,-1);
    if (!strcmp(code,cur_code)){
        char *config_lang = config(installer_locale_parameter);
        if (!yon_char_is_empty(config_lang)&&!strcmp(cur_code,config_lang)){
            if (gtk_tree_model_filter_convert_child_iter_to_iter(GTK_TREE_MODEL_FILTER(widgets->InstallerCountryFilter),iter,&itar)){
                gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->CountryLanguagesTree)),&itar);
            }
        }
        return 1;
    }
    return 0;

}

void yon_installer_widget_set_translation(GtkWidget *target){
    GObject *cur_widget = NULL;
    char *widget_text = NULL;
    if (GTK_IS_BUTTON(target)){
        cur_widget = G_OBJECT(target);
        widget_text = yon_char_new(gtk_button_get_label(GTK_BUTTON(cur_widget)));
    } else if (GTK_IS_LABEL(target)){
        cur_widget = G_OBJECT(target);
        widget_text = yon_char_new(gtk_label_get_label(GTK_LABEL(cur_widget)));
    } else if (GTK_IS_TREE_VIEW_COLUMN(target)){
        cur_widget = G_OBJECT(target);
        widget_text = yon_char_new(gtk_tree_view_column_get_title(GTK_TREE_VIEW_COLUMN(cur_widget)));
    } else if (GTK_IS_MENU_ITEM(target)){
        cur_widget = G_OBJECT(target);
        GList *list = gtk_container_get_children(GTK_CONTAINER(cur_widget));
        if (list) {
            GtkWidget *widget = target;
            g_list_free(list);
            if (GTK_IS_BOX(widget)){
                return;
            }
        }
        widget_text = yon_char_new(gtk_menu_item_get_label(GTK_MENU_ITEM(cur_widget)));
    } else return;
    g_object_set_data(G_OBJECT(cur_widget),"original_label",(void*)widget_text);
}

void yon_installer_translation_init(GtkBuilder *builder){

    GSList *list = gtk_builder_get_objects(builder);
    GSList *iter;
    for (iter = list; iter; iter = iter->next){
        if (GTK_IS_WIDGET(iter->data)){
            const char *tooltip = gtk_widget_get_tooltip_text(GTK_WIDGET(iter->data));
            if (!yon_char_is_empty(tooltip)){
                g_object_set_data(G_OBJECT(iter->data),"original_tooltip",(void*)yon_char_new(tooltip));
            }
        }
        GObject *cur_widget = NULL;
        const char *widget_text = NULL;
        if (GTK_IS_BUTTON(iter->data)){
            cur_widget = G_OBJECT(iter->data);
            widget_text = yon_char_new(gtk_button_get_label(GTK_BUTTON(cur_widget)));
        } else if (GTK_IS_LABEL(iter->data)){
            cur_widget = G_OBJECT(iter->data);
            widget_text = yon_char_new(gtk_label_get_label(GTK_LABEL(cur_widget)));
        } else if (GTK_IS_TREE_VIEW_COLUMN(iter->data)){
            cur_widget = G_OBJECT(iter->data);
            widget_text = yon_char_new(gtk_tree_view_column_get_title(GTK_TREE_VIEW_COLUMN(cur_widget)));
        } else if (GTK_IS_MENU_ITEM(iter->data)){
            cur_widget = G_OBJECT(iter->data);
            GList *list = gtk_container_get_children(GTK_CONTAINER(cur_widget));
            if (list) {
                GtkWidget *widget = list->data;
                g_list_free(list);
                if (GTK_IS_BOX(widget)){
                    continue;
                }
            }
            widget_text = yon_char_new(gtk_menu_item_get_label(GTK_MENU_ITEM(cur_widget)));
        } else continue;
            g_object_set_data(G_OBJECT(cur_widget),"original_label",(void*)widget_text);

    }
}

void yon_installer_update_translation(main_window *widgets){
    GtkBuilder *builder = widgets->builder;
    GSList *list = gtk_builder_get_objects(builder);
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->DocumentationMenuItem),"Label"));
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->AboutMenuItem),"Label"));
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->root_button),"Label"));
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->debug_button),"Label"));
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->ConfigurationModeMenuItem),"Label"));
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->EnableVNCMenuItem),"Label"));
    list = g_slist_append(list,g_object_get_data(G_OBJECT(widgets->EnableRDPMenuItem),"Label"));
    dictionary *diter = NULL;
    for_dictionaries (diter,widgets->PackagesMenu->buttons){
        GtkWidget *label = g_object_get_data(G_OBJECT(diter->data),"Label");
        list = g_slist_append(list,label);
    }
    GSList *iter;
    
    for (iter = list; iter; iter = iter->next){
        if (iter->data == widgets->LicenceLabel){
            yon_licence_load(widgets);
        } else if (GTK_IS_BUTTON(iter->data)){
            GtkWidget *cur_button = GTK_WIDGET(iter->data);
            char *source_label = g_object_get_data(G_OBJECT(cur_button),"original_label");
            if (!yon_char_is_empty(source_label)){
                gtk_button_set_label(GTK_BUTTON(cur_button),_(source_label));
            }

        } else if (GTK_IS_LABEL(iter->data)){
            GtkWidget *cur_label = GTK_WIDGET(iter->data);
            char *source_label = g_object_get_data(G_OBJECT(cur_label),"original_label");
            if (!yon_char_is_empty(source_label)){
                if (gtk_label_get_use_markup(GTK_LABEL(cur_label))){
                    gtk_label_set_markup(GTK_LABEL(cur_label),_(source_label));
                } else {
                    gtk_label_set_text(GTK_LABEL(cur_label),_(source_label));
                }
            }

        } else if (GTK_IS_MENU_ITEM(iter->data)){
            GtkWidget *cur_menu_item = GTK_WIDGET(iter->data);
            char *source_label = g_object_get_data(G_OBJECT(cur_menu_item),"original_label");
            if (!yon_char_is_empty(source_label)){
                gtk_menu_item_set_label(GTK_MENU_ITEM(cur_menu_item),_(source_label));
            }

        } else if (GTK_IS_TREE_VIEW_COLUMN(iter->data)){
            GObject *cur_column = G_OBJECT(iter->data);
            char *source_label = g_object_get_data(G_OBJECT(cur_column),"original_label");
            if (!yon_char_is_empty(source_label)){
                gtk_tree_view_column_set_title(GTK_TREE_VIEW_COLUMN(cur_column),_(source_label));
            }
        } else if (iter->data == widgets->LanguagesTree){
            yon_set_locales_list(widgets);
        }
        if (GTK_IS_WIDGET(iter->data)){
            const char *tooltip_text = g_object_get_data(G_OBJECT(iter->data),"original_tooltip");
            if (!yon_char_is_empty(tooltip_text)){
                gtk_widget_set_tooltip_text(GTK_WIDGET(iter->data),_(tooltip_text));
            }
        }
    }
    {
        GList *list = gtk_container_get_children(GTK_CONTAINER(widgets->DocumentationMenuItem));
        GList *container = gtk_container_get_children(list->data);
        
        GObject *cur_button = G_OBJECT(container->next->data);
        char *source_label = g_object_get_data(G_OBJECT(widgets->DocumentationMenuItem),"original_label");
        if (!yon_char_is_empty(source_label)){
            gtk_label_set_text(GTK_LABEL(cur_button),_(source_label));
        }
        g_list_free(list);
        g_list_free(container);
    }
    {
        GList *list = gtk_container_get_children(GTK_CONTAINER(widgets->AboutMenuItem));
        GList *container = gtk_container_get_children(list->data);
        
        GObject *cur_button = G_OBJECT(container->next->data);
        char *source_label = g_object_get_data(G_OBJECT(widgets->AboutMenuItem),"original_label");
        if (!yon_char_is_empty(source_label)){
            gtk_label_set_text(GTK_LABEL(cur_button),_(source_label));
        }
        g_list_free(list);
        g_list_free(container);
    }
    
}