#include "ubl-settings-system.h"

void on_locale_toggle(GtkCellRenderer *, gchar *path,language_window *window){
    GtkTreeIter iter, chiter;
    GtkTreeModel *model = GTK_TREE_MODEL(window->LanguagesList);
    gtk_tree_model_get_iter_from_string(window->LanguagesFilter,&chiter,path);
    gtk_tree_model_filter_convert_iter_to_child_iter(GTK_TREE_MODEL_FILTER(window->LanguagesFilter),&iter, &chiter);
    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;
    }
    yon_config_register(locale_parameter,locale_parameter_command,final);
    on_subwindow_close(self);
    yon_interface_update(widgets);
}

gboolean yon_locale_window_set_locales(struct locales_struct *data){
    if (!data)
        return G_SOURCE_REMOVE;
    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);
    free(data);
    return G_SOURCE_REMOVE;
}

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

void *yon_locales_load_func(language_window *window){
    char *config_value = config(locale_parameter);
    int config_parsed_size;
    config_str config_parsed = NULL;
    if (config_value){
        gtk_entry_set_text(GTK_ENTRY(window->ManualEntry),config_value);
        config_parsed = yon_char_parse(config_value,&config_parsed_size,",");
    }

    int size;
    config_str languages = yon_config_load(yon_debug_output("%s\n",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_unlock,window->LoadingSpinner);
    yon_char_parsed_free(config_parsed,config_parsed_size);
    g_thread_exit(NULL);
}

gboolean yon_filter(GtkTreeModel* model, GtkTreeIter *iter, language_window *window){
    char *code, *lang, *region;
    gtk_tree_model_get(model,iter,1,&code,2,&lang,3,&region,-1);
    const char *search_text = gtk_entry_get_text(GTK_ENTRY(window->SearchEntry));
    if (yon_char_is_empty(search_text)) return 1;
    gchar *search_utf = g_utf8_casefold(search_text,-1);
    gchar *search_normalized = g_utf8_strdown(g_utf8_normalize(search_utf,-1,G_NORMALIZE_DEFAULT),-1);
    gboolean lang_found = 0;
    if (!yon_char_is_empty(lang)){
        gchar *lang_utf = g_utf8_casefold(lang,-1);
        gchar *lang_normalized = g_utf8_strdown(g_utf8_normalize(lang_utf,-1,G_NORMALIZE_DEFAULT),-1);
        lang_found = !!strstr(lang_normalized,search_normalized);
    }
    gboolean region_found = 0;
    if (!yon_char_is_empty(region)){
        gchar *region_utf = g_utf8_casefold(region,-1);
        gchar *region_normalized = g_utf8_strdown(g_utf8_normalize(region_utf,-1,G_NORMALIZE_DEFAULT),-1);
        region_found = !!strstr(region_normalized,search_normalized);
    }

    return lang_found||region_found;
}

void on_filer_changed(GtkWidget *, language_window *window){
    gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(window->LanguagesFilter));
}

language_window *yon_language_window_new(){
    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->SearchEntry = yon_gtk_builder_get_widget(builder,"SearchEntry");
    window->ToggleCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"ToggleCell"));
    window->LanguagesList = GTK_LIST_STORE(gtk_builder_get_object(builder,"LanguagesList"));
    window->LanguagesFilter = gtk_tree_model_filter_new(GTK_TREE_MODEL(window->LanguagesList),NULL);

    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->SearchEntry),"changed",G_CALLBACK(on_filer_changed),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));
    gtk_tree_view_set_model(GTK_TREE_VIEW(window->LanguagesTree),window->LanguagesFilter);
    // gtk_tree_view_set_search_entry(GTK_TREE_VIEW(window->LanguagesTree),GTK_ENTRY(window->SearchEntry));
    gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(window->LanguagesFilter),(GtkTreeModelFilterVisibleFunc)yon_filter,window,NULL);

    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){
    language_window *window = yon_language_window_new();

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

    yon_gtk_window_setup(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->Window),ADD_LANGUAGE_TITLE_LABEL,main_icon,"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)){
        char *target;
        gtk_tree_model_get(model,&iter,3,&target,-1);
        char *locale_param = config(locale_parameter);
        char *temp = yon_char_remove_element(locale_param,target,",");
        if (!yon_char_is_empty(temp)){
            yon_config_register(locale_parameter,locale_parameter_command,temp);
            free(temp);
        } else {
            yon_config_remove_by_key(locale_parameter);

        }
        locale_param = config(language_parameter);
        if (!yon_char_is_empty(locale_param)&&!strcmp(locale_param,target)){
            yon_config_remove_by_key(language_parameter);
        }
        yon_interface_update(widgets);
    }
}