#include "ubl-settings-system.h"

config main_config;

//functions


void yon_interface_update(main_window *widgets){

    g_signal_handlers_block_by_func(G_OBJECT(widgets->IDEntry),G_CALLBACK(on_id_changed),widgets);
    g_signal_handlers_block_by_func(G_OBJECT(widgets->HostnameEntry),G_CALLBACK(on_hostname_changed),widgets);
    gtk_list_store_clear(widgets->LanguageList);
    gtk_entry_set_text(GTK_ENTRY(widgets->HostnameEntry),"");
    gtk_entry_set_text(GTK_ENTRY(widgets->IDEntry),"");
    gtk_entry_set_text(GTK_ENTRY(widgets->DomainEntry),"");
    int size;
    config_str rtn = yon_file_open(get_id_command,&size);
    rtn[0]=yon_char_divide_search(rtn[0],"\n",-1);
    gtk_entry_set_text(GTK_ENTRY(widgets->IDEntry),*rtn);
    char *hostname = yon_config_get_by_key(hostname_parameter);
    if (!yon_char_is_empty(hostname)){
        gtk_entry_set_text(GTK_ENTRY(widgets->HostnameEntry),hostname);
    }
    char *id = yon_config_get_by_key(id_parameter);
    if (id&&!strcmp(id,"random"))
        gtk_combo_box_set_active(GTK_COMBO_BOX(widgets->IDCombo),1);
    else if (id&&!strcmp(id,"hardware"))
        gtk_combo_box_set_active(GTK_COMBO_BOX(widgets->IDCombo),2);
    else if (id){
        gtk_entry_set_text(GTK_ENTRY(widgets->IDEntry),id);
        gtk_combo_box_set_active(GTK_COMBO_BOX(widgets->IDCombo),3);
    } else {
        gtk_combo_box_set_active(GTK_COMBO_BOX(widgets->IDCombo),0);
        gtk_widget_set_sensitive(widgets->IDEntry,0);
    }

    char *domain = config(DOMAIN);
    if (!yon_char_is_empty(domain)){
        gtk_entry_set_text(GTK_ENTRY(widgets->DomainEntry),domain);
    }

    {
        char *config_locale = config(locale_parameter);
        char *config_languages = config(language_parameter);
        if (yon_char_is_empty(config_locale)||yon_config_check_ignore(locale_parameter)){
            gtk_switch_set_active(GTK_SWITCH(widgets->LocaleDefaultSwitch),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);
                }
            }
        }
    }

    g_signal_handlers_unblock_by_func(G_OBJECT(widgets->IDEntry),G_CALLBACK(on_id_changed),widgets);
    g_signal_handlers_unblock_by_func(G_OBJECT(widgets->HostnameEntry),G_CALLBACK(on_hostname_changed),widgets);
}

void yon_gtk_windget_set_sensitive_from_entry_emptiness(GtkEntry *self, GtkWidget *target){
    if (yon_char_is_empty(gtk_entry_get_text(self))){
        gtk_widget_set_sensitive(target,0);
    } else {
        gtk_widget_set_sensitive(target,1);
    }
}

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

    }
    gtk_list_store_set(GTK_LIST_STORE(model),&fiter,0,!status,-1);
    if (!status){
        yon_config_register(language_parameter,language_parameter_command,target);
    } else {
        yon_config_remove_by_key(language_parameter);
    }
}

void on_hostname_changed(GtkEntry *self, main_window *){
    char *text = (char*)gtk_entry_get_text(self);
    if (yon_config_get_by_key(hostname_parameter)){
        yon_config_set(hostname_parameter,text);
    } else {
        yon_config_register(hostname_parameter,HOSTNAME_get_command,text);
    }
}

void on_id_combo_toggled(GtkComboBox *self, main_window *widgets){
    int id = gtk_combo_box_get_active(self);
    if (id==2||id==1){ 
        if (yon_config_get_by_key(id_parameter)){
            yon_config_set(id_parameter, id == 1 ? "random" : "hardware");
        } else {
            yon_config_register(id_parameter,MACHINEID_get_command, id == 1 ? "random":"hardware");
        }
    }
    if (id<3){
        gtk_widget_set_sensitive(widgets->IDEntry,0);
    }
    else {
        gtk_widget_set_sensitive(widgets->IDEntry,1);
    }
}

void on_id_changed(GtkEntry *self, main_window *widgets){
    char *text = (char*)gtk_entry_get_text(self);
    if (strcmp(text,"")){
        if (yon_config_get_by_key(id_parameter)){
            yon_config_set(id_parameter,text);
        } else {
            yon_config_register(id_parameter,MACHINEID_get_command,text);
        }
        if (!main_config.lock_save_global)
            gtk_widget_set_sensitive(widgets->SaveGlobalMenuItem,1);
        if (!main_config.lock_save_global&&!main_config.lock_save_global)
            gtk_widget_set_sensitive(widgets->SaveMenuItem,1);
        if (!main_config.lock_save_local)
            gtk_widget_set_sensitive(widgets->SaveLocalMenuItem,1);
        gtk_widget_set_sensitive(widgets->IDCopyButton,1);
        yon_ubl_status_box_render(INSERT_LABEL,BACKGROUND_IMAGE_SUCCESS_TYPE);
    } else {
        gtk_widget_set_sensitive(widgets->SaveGlobalMenuItem,0);
        gtk_widget_set_sensitive(widgets->SaveMenuItem,0);
        gtk_widget_set_sensitive(widgets->SaveLocalMenuItem,0);
        gtk_widget_set_sensitive(widgets->IDCopyButton,0);
        yon_ubl_status_box_render(ID_EMPTY_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
    }

}

void on_id_copy(GtkButton *, main_window *widgets){
    GtkClipboard *clipboard = gtk_clipboard_get_default(gdk_display_get_default());
    const char *clipboard_id = gtk_entry_get_text(GTK_ENTRY(widgets->IDEntry));
    gtk_clipboard_set_text(clipboard,clipboard_id,strlen(clipboard_id));
    yon_ubl_status_box_render(COPY_SUCCESS_LABEL,BACKGROUND_IMAGE_SUCCESS_TYPE);
}

void on_terminal_done(VteTerminal *, gint status, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    GtkWidget *window = yon_dictionary_get_data(dict->first->next,GtkWidget*);
    if (!status){
        gtk_widget_destroy(window);
        on_config_reload(NULL,widgets);
    }
}

void on_terminal_command_ended(VteTerminal *, gint status, domain_info_window *window){
    // yon_ubl_status_box_despawn_infinite(GTK_CONTAINER(window->StatusBox));
    if (!status){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),yon_char_get_localised_from_lib(SUCCESS_LABEL),0,BACKGROUND_IMAGE_SUCCESS_TYPE);
    } else {
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),yon_char_get_localised_from_lib(FAIL_LABEL),0,BACKGROUND_IMAGE_FAIL_TYPE);
    }
}

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);
        gtk_widget_set_sensitive(GTK_WIDGET(widgets->locale_menu->buttons->first->next->data),1);
    } else {
        gtk_widget_set_sensitive(widgets->LocaleRemoveButton,0);
        gtk_widget_set_sensitive(GTK_WIDGET(widgets->locale_menu->buttons->first->next->data),0);
    }
    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(language_parameter,language_parameter_command,target);
            }
        }
        if (!yon_char_is_empty(locales)){
            yon_config_register(locale_parameter,locale_parameter_command,locales);
        }
    }
}

void on_locale_selection_changed(GtkWidget *,main_window *widgets){
    GtkTreeModel *model;
    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);
        gtk_widget_set_sensitive(GTK_WIDGET(widgets->locale_menu->buttons->first->next->data),1);
    } else {
        gtk_widget_set_sensitive(widgets->LocaleRemoveButton,0);
        gtk_widget_set_sensitive(GTK_WIDGET(widgets->locale_menu->buttons->first->next->data),0);
    }
}

main_window *yon_main_window_complete(main_window *widgets){
    /* Widgets getting | Получение виджетов */
    widgets = yon_remalloc(widgets,sizeof(main_window)); 
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path);
    gtk_box_pack_start(GTK_BOX(widgets->InterfaceBox),yon_gtk_builder_get_widget(builder,"BoxMain"),1,1,0);

    widgets->HostnameEntry = yon_gtk_builder_get_widget(builder,"HostnameEntry");
    widgets->IDCombo = yon_gtk_builder_get_widget(builder,"IDCombo");
    widgets->IDEntry = yon_gtk_builder_get_widget(builder,"IDEntry");
    widgets->IDCopyButton = yon_gtk_builder_get_widget(builder,"IDCopyButton");

    widgets->LocaleTree = yon_gtk_builder_get_widget(builder,"LocaleTree");
    widgets->LocaleAddButton = yon_gtk_builder_get_widget(builder,"LocaleAddButton");
    widgets->LocaleRemoveButton = yon_gtk_builder_get_widget(builder,"LocaleRemoveButton");
    widgets->LocaleDefaultSwitch = yon_gtk_builder_get_widget(builder,"LocaleDefaultSwitch");
    widgets->LocaleCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"LocaleCell"));

    widgets->FindButton = yon_gtk_builder_get_widget(builder,"FindButton");
    widgets->DomainButton = yon_gtk_builder_get_widget(builder,"DomainButton");
    widgets->DomainEntry = yon_gtk_builder_get_widget(builder,"DomainEntry");

    widgets->LanguageList = GTK_LIST_STORE(gtk_builder_get_object(builder,"LanguageList"));

    widgets->DocumentationMenuItem = yon_ubl_menu_item_documentation_new(DOCUMENTATION_LABEL);
    widgets->AboutMenuItem = yon_ubl_menu_item_about_new(ABOUT_LABEL);

    /* Widget registration for config monitoring | Регистрация виджетов для мониторинга конфига */

    /* Signal connection | Присоединение сигналов */

    widgets->locale_menu = yon_rmb_menu_setup(widgets->LocaleTree,NULL,NULL,
    ADD_LANGUAGE_TOOLTIP_LABEL,add_icon_path,G_CALLBACK(on_language_open),widgets,
    REMOVE_LANGUAGE_LABEL,remove_icon_path,G_CALLBACK(on_language_remove),widgets,
    NULL);

    g_signal_connect(G_OBJECT(widgets->LoadGlobalMenuItem),"activate",G_CALLBACK(yon_config_global_load),widgets);
    g_signal_connect(G_OBJECT(widgets->LoadLocalMenuItem),"activate",G_CALLBACK(yon_config_local_load),widgets);
    g_signal_connect(G_OBJECT(widgets->LoadCustomMenuItem),"activate",G_CALLBACK(yon_config_custom_load),widgets);

    g_signal_connect(G_OBJECT(widgets->SaveMenuItem),"activate",G_CALLBACK(yon_config_global_local_save),widgets);
    g_signal_connect(G_OBJECT(widgets->SaveGlobalMenuItem),"activate",G_CALLBACK(yon_config_global_save),widgets);
    g_signal_connect(G_OBJECT(widgets->SaveLocalMenuItem),"activate",G_CALLBACK(yon_config_local_save),widgets);
    g_signal_connect(G_OBJECT(widgets->SaveCustomMenuItem),"activate",G_CALLBACK(yon_config_custom_save),widgets);

    g_signal_connect(G_OBJECT(widgets->LocaleTree),"cursor-changed",G_CALLBACK(on_locale_selection_changed),widgets);

    g_signal_connect(G_OBJECT(widgets->HostnameEntry),"changed",G_CALLBACK(on_hostname_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->IDCombo),"changed",G_CALLBACK(on_id_combo_toggled),widgets);
    g_signal_connect(G_OBJECT(widgets->IDEntry),"changed",G_CALLBACK(on_id_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->IDCopyButton),"clicked",G_CALLBACK(on_id_copy),widgets);
    g_signal_connect(G_OBJECT(widgets->LocaleAddButton),"clicked",G_CALLBACK(on_language_open),widgets);
    g_signal_connect(G_OBJECT(widgets->LocaleRemoveButton),"clicked",G_CALLBACK(on_language_remove),widgets);
    g_signal_connect(G_OBJECT(widgets->LocaleDefaultSwitch),"state-set",G_CALLBACK(on_language_default_toggled),widgets);
    g_signal_connect(G_OBJECT(widgets->LocaleCell),"toggled",G_CALLBACK(on_locale_toggled),widgets);

    g_signal_connect(G_OBJECT(widgets->DomainButton),"clicked",G_CALLBACK(on_domain_opened),widgets);
    g_signal_connect(G_OBJECT(widgets->DomainEntry),"icon-press",G_CALLBACK(on_main_window_domain_status_clicked),widgets);
    g_signal_connect(G_OBJECT(widgets->DomainEntry),"changed",G_CALLBACK(yon_gtk_windget_set_sensitive_from_entry_emptiness),widgets->DomainButton);

    g_signal_connect(G_OBJECT(widgets->DomainEntry),"focus-out-event",G_CALLBACK(on_domain_address_save),NULL);
    
    g_signal_connect(G_OBJECT(widgets->FindButton),"clicked",G_CALLBACK(on_find_domains_clicked),widgets);

    on_locale_selection_changed(NULL,widgets);

    on_check_domain_connected(NULL, widgets);
    
    if (main_config.lock_load_global == 1){
        gtk_widget_set_sensitive(widgets->LoadGlobalMenuItem,0);
    }
    if (main_config.lock_save_global == 1){
        gtk_widget_set_sensitive(widgets->SaveGlobalMenuItem,0);
        gtk_widget_set_sensitive(widgets->SaveMenuItem,0);
    }
    if (main_config.lock_save_local == 1){
        gtk_widget_set_sensitive(widgets->SaveLocalMenuItem,0);
        gtk_widget_set_sensitive(widgets->SaveMenuItem,0);
    }
    yon_config_local_load(NULL,widgets);
    char *domain = yon_config_get_by_key(DOMAIN);
    if (!yon_char_is_empty(domain)){
        gtk_entry_set_text(GTK_ENTRY(widgets->DomainEntry),domain);
    }
	yon_save_window_set_postsave_function(on_save_done,widgets);
    return widgets;
}

void yon_config_init(){
    main_config.languages = g_hash_table_new(g_str_hash,g_str_equal);
    int size;
    config_str languages = yon_config_load(languages_command,&size);
    for (int i=0;i<size;i++){
        yon_char_remove_last_symbol(languages[i],'\n');
        int parsed_size;
        config_str parsed = yon_char_parse(languages[i],&parsed_size,"|");
        g_hash_table_insert(main_config.languages,yon_char_new(parsed[0]),yon_char_new(languages[i]));
        yon_char_parsed_free(parsed,parsed_size);
    }
    yon_char_parsed_free(languages,size);
}

int main(int argc, char *argv[]){
    setlocale(LC_ALL, "");
    textdomain (LocaleName); 
    yon_config_init();
    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;
	yon_ubl_setup_arguments(argc,argv,&unfound,&size,NULL);
    gtk_init(&argc,&argv); 
    template_main_window *widgets = yon_ubl_window_setup(); 
    yon_root_button_setup(widgets,argv,argc);
    yon_main_window_complete((main_window*)widgets);
	yon_window_config_load(config_path);
    gtk_main();
}