#include "ubl-settings-bootloader.h"

config main_config;

//functions

void on_save_done(main_window *, config_str output, int size){
	char *final_output = yon_char_parsed_to_string(output,size,"\n");
	if (final_output){
		printf("%s\n",final_output);
		free(final_output);
	}
	yon_char_parsed_free(output,size);
	textdomain(template_ui_LocaleName);
	switch (main_config.save_config){
		case 0:
			yon_ubl_status_box_render(yon_char_get_localised_from_lib(GLOBAL_SAVE_SUCCESS_LABEL),BACKGROUND_IMAGE_SUCCESS_TYPE);
			break;
		case 1:
			yon_ubl_status_box_render(yon_char_get_localised_from_lib(LOCAL_SAVE_SUCCESS_LABEL),BACKGROUND_IMAGE_SUCCESS_TYPE);
			break;
		case 3:
			yon_ubl_status_box_render(yon_char_get_localised_from_lib(GLOBAL_LOCAL_SAVE_SUCCESS_LABEL),BACKGROUND_IMAGE_SUCCESS_TYPE);
			break;
	}
	textdomain(LocaleName);
	
}

void yon_save_window_hide_passwords(template_saving_window *window){
    GtkTreeIter iter;

    for_iter(GTK_TREE_MODEL(window->list),&iter){
        char *target, *old_val, *new_val;
        gtk_tree_model_get(GTK_TREE_MODEL(window->list),&iter,YON_SAVE_PARAMETER,&target,YON_SAVE_OLD,&old_val,YON_SAVE_NEW,&new_val,-1);
        if (strstr(target,GRUB_PASSWORD_search)){
            if (!yon_char_is_empty(old_val)) old_val="<s>******</s>"; else old_val="";
            if (!yon_char_is_empty(new_val)) new_val="******"; else new_val="";
            char *united = yon_char_unite(old_val,"\n",new_val,NULL);
            gtk_list_store_set(window->list,&iter,YON_SAVE_COMPARE,united,-1);
            free(united);
        }
    }
}

void on_config_global_local_save(GtkWidget *, main_window *){
    main_config.save_config=3;
    template_saving_window *window = yon_save_proceed(NULL,YON_CONFIG_BOTH,config_get_global_command,NULL);
	if (window){
        yon_save_window_hide_passwords(window);
    };
}

void on_config_local_save(GtkWidget *, main_window *){
    main_config.save_config=1;
    template_saving_window *window = yon_save_proceed("system",YON_CONFIG_LOCAL,config_get_local_command,NULL);
	if (window){
        yon_save_window_hide_passwords(window);
    };
}

void on_config_global_save(GtkWidget *, main_window *){
    main_config.save_config=0;
    template_saving_window *window = yon_save_proceed("global",YON_CONFIG_GLOBAL,config_get_global_command,NULL);
	if (window){
        yon_save_window_hide_passwords(window);
    };
}

void on_config_custom_save(GtkWidget *, main_window *){
    main_config.save_config=1;
	template_saving_window *window = yon_save_proceed(NULL,YON_CONFIG_CUSTOM,yon_config_get_custom_command("system"),NULL);
	if (window){
        yon_save_window_hide_passwords(window);
    };
}

void on_config_local_load(GtkWidget *,main_window *widgets){
    yon_load_proceed(YON_CONFIG_LOCAL);
    yon_interface_update(widgets);
    main_config.load_mode=YON_CONFIG_LOCAL;
}

void on_config_global_load(GtkWidget *,main_window *widgets){
    yon_load_proceed(YON_CONFIG_GLOBAL);
    yon_interface_update(widgets);
    main_config.load_mode=YON_CONFIG_GLOBAL;
}

void on_config_custom_load(GtkWidget *,main_window *widgets){
	yon_load_proceed(YON_CONFIG_CUSTOM);
	textdomain(template_ui_LocaleName);
	textdomain(LocaleName);
	main_config.load_mode=YON_CONFIG_CUSTOM;
    yon_interface_update(widgets);
}

void yon_load_proceed(YON_CONFIG_TYPE type){
    yon_config_clean();
    if (!yon_char_is_empty(config_get_default_command))
        yon_config_load_config(YON_CONFIG_DEFAULT,config_get_default_command,NULL);
    if (type==YON_CONFIG_GLOBAL){
		if (yon_config_load_config(type,config_get_global_command,NULL)){
            yon_ubl_status_box_render(yon_char_get_localised_from_lib(GLOBAL_LOAD_SUCCESS_LABEL),BACKGROUND_IMAGE_SUCCESS_TYPE);
        }
	} else if (type==YON_CONFIG_LOCAL){
		if (yon_config_load_config(type,config_get_local_command,NULL)){
            yon_ubl_status_box_render(yon_char_get_localised_from_lib(LOCAL_LOAD_SUCCESS_LABEL),BACKGROUND_IMAGE_SUCCESS_TYPE);
        }
    } else if (type==YON_CONFIG_CUSTOM){
		char *path="";
        textdomain(template_ui_LocaleName);
		GtkWidget *dialog = gtk_file_chooser_dialog_new(template_app_information.app_title,NULL,GTK_FILE_CHOOSER_ACTION_SAVE,CANCEL_LABEL,GTK_RESPONSE_CANCEL,OPEN_LABEL,GTK_RESPONSE_ACCEPT,NULL);
        textdomain(LocaleName);
        gtk_window_set_icon_name(GTK_WINDOW(dialog),"com.ublinux.ubl-settings-services");
        gtk_window_set_title(GTK_WINDOW(dialog),TITLE_LABEL);
        GtkFileFilter *filter = gtk_file_filter_new();
		gtk_file_filter_add_pattern(filter,"*.ini");
        gtk_file_filter_set_name(filter, "*.ini");
		gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog),filter);
		gtk_widget_show(dialog);
		int response = gtk_dialog_run(GTK_DIALOG(dialog));
		if (response == GTK_RESPONSE_ACCEPT){
			char *file = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
			if (!yon_char_is_empty(file)){
				path=file;
			}
			gtk_widget_destroy(dialog);
		} else {
			gtk_widget_destroy(dialog);
		}
        char *command = yon_config_get_custom_command(path);
		if (yon_config_load_config(type,command,NULL)){
            yon_ubl_status_box_render(yon_char_get_localised_from_lib(yon_char_get_localised_from_lib(LOCAL_LOAD_SUCCESS_LABEL)),BACKGROUND_IMAGE_SUCCESS_TYPE);
        }
	}
}

char *yon_bootloader_get_os_name(char *parameter){
    bind_textdomain_codeset("ublinux-init-grub-functions","UTF-8");
    textdomain("ublinux-init-grub-functions");
    char *final_os_name = NULL;
    int size;
    config_str menu_entries = yon_config_load(get_menus_entry_command,&size);
    for (int i=0;i<size;i++){
        yon_char_remove_last_symbol(menu_entries[i],'\n');
        int parsed_size;
        config_str parsed = yon_char_parse(menu_entries[i],&parsed_size,";");
        if (!strcmp(parsed[0],parameter)){
            char *name = strstr(_(parsed[1]),">");
            if (!yon_char_is_empty(name)){
                name++;
                final_os_name = yon_char_new(name);
            } else {
                final_os_name = yon_char_new(_(parsed[1]));
            }
        }
        yon_char_parsed_free(parsed,parsed_size);
    }
    yon_char_parsed_free(menu_entries,size);
    textdomain(LocaleName);
    return final_os_name;
}

void yon_interface_update(main_window *widgets){
    gtk_list_store_clear(widgets->BootUsersList);
    gtk_list_store_clear(widgets->BootRingtoneList);
    gtk_list_store_clear(widgets->KernelParametersList);
    gtk_list_store_clear(widgets->InputTerminalList);
    gtk_list_store_clear(widgets->OutputTerminalList);
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->BootUsersTree),NULL);
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->BootRingtoneTree),NULL);
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->KernelParametersTree),NULL);
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->InputTerminalTree),NULL);
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->OutputTerminalTree),NULL);

    char *timeout = config(GRUB_TIMEOUT_parameter);
    if (!yon_char_is_empty(timeout)){
        gtk_spin_button_set_value(GTK_SPIN_BUTTON(widgets->BootSelectionTimerSpin),atof(timeout));
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widgets->BootSelectionTimerCheck),1);
    } else {
        gtk_spin_button_set_value(GTK_SPIN_BUTTON(widgets->BootSelectionTimerSpin),0);
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widgets->BootSelectionTimerCheck),0);
    }
    {
        char *display_mode = config(GRUB_BOOT_SILENT_parameter);
        if (!yon_char_is_empty(display_mode)){
            gtk_combo_box_set_active_id(GTK_COMBO_BOX(widgets->BootDisplayModeCombo),display_mode);
        }
        else {
            gtk_combo_box_set_active(GTK_COMBO_BOX(widgets->BootDisplayModeCombo),0);

        }
    }
    {
        char *grub_default = config(GRUB_DEFAULT_parameter);
        if (!yon_char_is_empty(grub_default)) {
            char *os_name = yon_bootloader_get_os_name(grub_default);
            if (!yon_char_is_empty(os_name)){
                gtk_entry_set_text(GTK_ENTRY(widgets->OSDefaultEntry),os_name);
                free(os_name);
            }
        } else {
            gtk_entry_set_text(GTK_ENTRY(widgets->OSDefaultEntry),DEFAULT_MENU_ITEM_LABEL);
        }
    }
    {
        GtkTreeIter iter;
        int users_size;
        int admins_size;
        char *admins = config(GRUB_SUPERUSERS_parameter);
        config_str users = yon_config_get_all_by_key(GRUB_PASSWORD_search,&users_size);
        config_str admins_parsed = yon_char_parse(admins,&admins_size,",");
        for (int i=0;i<users_size;i++){
            yon_char_remove_last_symbol(users[i],'\n');
            char *password = yon_char_new(users[i]);
            char *username = yon_char_divide_search(password,"=",-1);
            free(yon_char_divide_search(username,"[",-1));
            yon_char_remove_last_symbol(username,']');
            gtk_list_store_append(widgets->BootUsersList,&iter);
            gtk_list_store_set(widgets->BootUsersList,&iter,0,yon_char_parsed_check_exist(admins_parsed,admins_size,username)>-1,1,username,2,"******",-1);

        }
    }
    {
        GtkTreeIter iter;
        int ringtones_size;
        config_str standard_ringtones = yon_resource_open_file(melody_path,&ringtones_size);
        for (int i=1;i<ringtones_size;i++){
            yon_char_remove_last_symbol(standard_ringtones[i],'\n');
            char *code = yon_char_new(standard_ringtones[i]);
            char *key = yon_char_divide_search(code,";",-1);
            gtk_list_store_append(widgets->BootRingtoneList,&iter);
            gtk_list_store_set(widgets->BootRingtoneList,&iter,0,0,1,key,2,code,-1);
        }
        char *ringtone = config(GRUB_PLAY_parameter);
        gsize size=0;
        config_str codes = yon_window_config_get_section("melodies",&size);

        for (gsize i=0;i<size;i++){
            char *cur_code = NULL;
            char *name = yon_char_new(codes[(int)i]);
            yon_window_config_get_parameter("melodies",name,&cur_code,YON_TYPE_STRING);
            int found = 0;
            for_iter(GTK_TREE_MODEL(widgets->BootRingtoneList),&iter){
                char *key;
                gtk_tree_model_get(GTK_TREE_MODEL(widgets->BootRingtoneList),&iter,1,&key,-1);
                if (!strcmp(key,name)){
                    found = 1;
                    break;
                }
            }
            if (!found){
                gtk_list_store_append(widgets->BootRingtoneList,&iter);
            }
                gtk_list_store_set(widgets->BootRingtoneList,&iter,0,!yon_char_is_empty(ringtone)&&!strcmp(ringtone,cur_code),1,name,2,cur_code,3,1,-1);
            free(cur_code);
            free(name);
        }
        if (size) yon_char_parsed_free(codes,size);
    }
    {
        int size;
        GtkTreeIter iter;

        char *parameter = config(GRUB_CMDLINE_LINUX_parameter);
        config_str parameters = yon_char_parse(parameter,&size," ");
        for (int i=1;i<main_config.kernel_size;i++){
            char *description = yon_char_new(main_config.kernel_parameters[i]);
            char *cur_parameter = yon_char_divide_search(description,";",-1);
            gtk_list_store_append(widgets->KernelParametersList,&iter);
            gtk_list_store_set(widgets->KernelParametersList,&iter,0,yon_char_parsed_check_exist(parameters,size,cur_parameter)>-1,1,cur_parameter,2,_(description),-1);
        }
        if (yon_char_is_empty(parameter)) parameter="";
        gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),parameter);
    }
    {
        int size;
        GtkTreeIter iter;

        char *parameter = config(GRUB_TERMINAL_INPUT_parameter);
        config_str parameters = yon_char_parse(parameter,&size," ");
        for (int i=1;i<main_config.input_size;i++){
            char *description = yon_char_new(main_config.input_parameters[i]);
            char *cur_parameter = yon_char_divide_search(description,";",-1);
            gtk_list_store_append(widgets->InputTerminalList,&iter);
            gtk_list_store_set(widgets->InputTerminalList,&iter,0,yon_char_parsed_check_exist(parameters,size,cur_parameter)>-1,1,cur_parameter,2,_(description),-1);
        }
        if (yon_char_is_empty(parameter)) parameter="";
        gtk_entry_set_text(GTK_ENTRY(widgets->InputTerminalEntry),parameter);
    }
    {
        int size;
        GtkTreeIter iter;

        char *parameter = config(GRUB_TERMINAL_OUTPUT_parameter);
        config_str parameters = yon_char_parse(parameter,&size," ");
        for (int i=1;i<main_config.output_size;i++){
            char *description = yon_char_new(main_config.output_parameters[i]);
            char *cur_parameter = yon_char_divide_search(description,";",-1);
            gtk_list_store_append(widgets->OutputTerminalList,&iter);
            gtk_list_store_set(widgets->OutputTerminalList,&iter,0,yon_char_parsed_check_exist(parameters,size,cur_parameter)>-1,1,cur_parameter,2,_(description),-1);
        }
        if (yon_char_is_empty(parameter)) parameter="";
        gtk_entry_set_text(GTK_ENTRY(widgets->OutputTerminalEntry),parameter);
    }
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->BootUsersTree),GTK_TREE_MODEL(widgets->BootUsersList));
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->BootRingtoneTree),GTK_TREE_MODEL(widgets->BootRingtoneList));
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->KernelParametersTree),GTK_TREE_MODEL(widgets->KernelParametersList));
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->InputTerminalTree),GTK_TREE_MODEL(widgets->InputTerminalList));
    gtk_tree_view_set_model(GTK_TREE_VIEW(widgets->OutputTerminalTree),GTK_TREE_MODEL(widgets->OutputTerminalList));
}

void on_kernel_parameter_switch(GtkCellRenderer *, char *path, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->KernelParametersList);

    if (gtk_tree_model_get_iter_from_string(model,&iter,path)){
        int status;
        char *parameter;

        gtk_tree_model_get(model,&iter,0,&status,1,&parameter,-1);
        gtk_list_store_set(widgets->KernelParametersList,&iter,0,!status,-1);
        char *config_param = config(GRUB_CMDLINE_LINUX_parameter);
        if (!yon_char_is_empty(config_param)){
            int size;
            config_str parsed = yon_char_parse(config_param,&size," ");
            switch (status){
                case 0:{
                    if (strstr(parameter,"=")){
                        char *param_copy = yon_char_new(parameter);
                        char *cur_param = yon_char_divide_search(param_copy,"=",-1);
                        free(param_copy);
                        GtkTreeIter itar;
                        for_iter(GTK_TREE_MODEL(widgets->KernelParametersList),&itar){
                            char *target;
                            gtk_tree_model_get(GTK_TREE_MODEL(widgets->KernelParametersList),&itar,1,&target,-1);
                            GtkTreePath *cur_path=gtk_tree_model_get_path(GTK_TREE_MODEL(widgets->KernelParametersList),&iter), *compare_path=gtk_tree_model_get_path(GTK_TREE_MODEL(widgets->KernelParametersList),&itar);
                            if (strstr(target,cur_param)&&strstr(target,"=")&&gtk_tree_path_compare(cur_path,compare_path)){
                                gtk_list_store_set(widgets->KernelParametersList,&itar,0,0,-1);
                                int pos = yon_char_parsed_check_exist(parsed,size,target);
                                if (pos>-1){
                                    if (size>1){
                                        parsed = yon_char_parsed_rip(parsed,&size,pos);
                                        char *final = yon_char_parsed_to_string(parsed,size," ");
                                        yon_config_register(GRUB_CMDLINE_LINUX_parameter,GRUB_CMDLINE_LINUX_command,final);
                                        gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),final);
                                        free(final);
                                    } else {
                                        yon_char_parsed_free(parsed,size);
                                        size=0;
                                        parsed=NULL;
                                        gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),"");
                                        yon_config_remove_by_key(GRUB_CMDLINE_LINUX_parameter);
                                    }
                                }
                            }
                            gtk_tree_path_free(cur_path);
                            gtk_tree_path_free(compare_path);

                        }
                        free(cur_param);
                    }
                        int pos = yon_char_parsed_check_exist(parsed,size,parameter);
                        if (pos == -1){
                            yon_char_parsed_add_or_create_if_exists(parsed,&size,parameter);
                            char *final = yon_char_parsed_to_string(parsed,size," ");
                            yon_config_register(GRUB_CMDLINE_LINUX_parameter,GRUB_CMDLINE_LINUX_command,final);
                            gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),final);
                            free(final);
                        }
                    }break;
                case 1:{
                        int pos = yon_char_parsed_check_exist(parsed,size,parameter);
                        if (pos>-1){
                            if (size>1){
                                parsed = yon_char_parsed_rip(parsed,&size,pos);
                                char *final = yon_char_parsed_to_string(parsed,size," ");
                                yon_config_register(GRUB_CMDLINE_LINUX_parameter,GRUB_CMDLINE_LINUX_command,final);
                                gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),final);
                                free(final);
                            } else {
                                gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),"");
                                yon_config_remove_by_key(GRUB_CMDLINE_LINUX_parameter);
                            }
                        }
                    } break;
            }

        } else if (status==0) {
            yon_config_register(GRUB_CMDLINE_LINUX_parameter,GRUB_CMDLINE_LINUX_command,parameter);
            gtk_entry_set_text(GTK_ENTRY(widgets->CommandLineParametersEntry),parameter);
        }
    }

}

void on_input_option_switch(GtkCellRenderer *,char *path, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->InputTerminalList);

    if (gtk_tree_model_get_iter_from_string(model,&iter,path)){
        int status;
        char *parameter;

        gtk_tree_model_get(model,&iter,0,&status,1,&parameter,-1);
        gtk_list_store_set(widgets->InputTerminalList,&iter,0,!status,-1);
        
        char *config_param = config(GRUB_TERMINAL_INPUT_parameter);
        if (!yon_char_is_empty(config_param)){
            int size;
            config_str parsed = yon_char_parse(config_param,&size," ");
            switch (status){
                case 0:{
                        int pos = yon_char_parsed_check_exist(parsed,size,parameter);
                        if (pos == -1){
                            yon_char_parsed_add_or_create_if_exists(parsed,&size,parameter);
                            char *final = yon_char_parsed_to_string(parsed,size," ");
                            yon_config_register(GRUB_TERMINAL_INPUT_parameter,GRUB_TERMINAL_INPUT_command,final);
                            gtk_entry_set_text(GTK_ENTRY(widgets->InputTerminalEntry),final);
                            free(final);
                        }
                    }break;
                case 1:{
                        int pos = yon_char_parsed_check_exist(parsed,size,parameter);
                        if (pos>-1){
                            if (size>1){
                                parsed = yon_char_parsed_rip(parsed,&size,pos);
                                char *final = yon_char_parsed_to_string(parsed,size," ");
                                yon_config_register(GRUB_TERMINAL_INPUT_parameter,GRUB_TERMINAL_INPUT_command,final);
                                gtk_entry_set_text(GTK_ENTRY(widgets->InputTerminalEntry),final);
                                free(final);
                            } else {
                                gtk_entry_set_text(GTK_ENTRY(widgets->InputTerminalEntry),"");
                                yon_config_remove_by_key(GRUB_TERMINAL_INPUT_parameter);
                            }
                        }
                    } break;
            }

        } else if (status==0) {
            yon_config_register(GRUB_TERMINAL_INPUT_parameter,GRUB_TERMINAL_INPUT_command,parameter);
            gtk_entry_set_text(GTK_ENTRY(widgets->InputTerminalEntry),parameter);
        }
    }

}

void on_output_option_switch(GtkCellRenderer *,char *path, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->OutputTerminalList);

    if (gtk_tree_model_get_iter_from_string(model,&iter,path)){
        int status;
        char *parameter;

        gtk_tree_model_get(model,&iter,0,&status,1,&parameter,-1);
        gtk_list_store_set(widgets->OutputTerminalList,&iter,0,!status,-1);
        
        char *config_param = config(GRUB_TERMINAL_OUTPUT_parameter);
        if (!yon_char_is_empty(config_param)){
            int size;
            config_str parsed = yon_char_parse(config_param,&size," ");
            switch (status){
                case 0:{
                        int pos = yon_char_parsed_check_exist(parsed,size,parameter);
                        if (pos == -1){
                            yon_char_parsed_add_or_create_if_exists(parsed,&size,parameter);
                            char *final = yon_char_parsed_to_string(parsed,size," ");
                            yon_config_register(GRUB_TERMINAL_OUTPUT_parameter,GRUB_TERMINAL_OUTPUT_command,final);
                            gtk_entry_set_text(GTK_ENTRY(widgets->OutputTerminalEntry),final);
                            free(final);
                        }
                    }break;
                case 1:{
                        int pos = yon_char_parsed_check_exist(parsed,size,parameter);
                        if (pos>-1){
                            if (size>1){
                                parsed = yon_char_parsed_rip(parsed,&size,pos);
                                char *final = yon_char_parsed_to_string(parsed,size," ");
                                yon_config_register(GRUB_TERMINAL_OUTPUT_parameter,GRUB_TERMINAL_OUTPUT_command,final);
                                gtk_entry_set_text(GTK_ENTRY(widgets->OutputTerminalEntry),final);
                                free(final);
                            } else {
                                gtk_entry_set_text(GTK_ENTRY(widgets->OutputTerminalEntry),"");
                                yon_config_remove_by_key(GRUB_TERMINAL_OUTPUT_parameter);
                            }
                        }
                    } break;
            }

        } else if (status==0) {
            yon_config_register(GRUB_TERMINAL_OUTPUT_parameter,GRUB_TERMINAL_OUTPUT_command,parameter);
            gtk_entry_set_text(GTK_ENTRY(widgets->OutputTerminalEntry),parameter);
        }
    }

}

void on_tree_view_selection_changed(GtkWidget *self, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model;
    if (self == widgets->BootUsersTree){
        if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->BootUsersTree)),&model,&iter)) {
            gtk_widget_set_sensitive(widgets->BootUsersEditButton,1);
                gtk_widget_set_sensitive(widgets->BootUsersRemoveButton,1);
        } else {
            gtk_widget_set_sensitive(widgets->BootUsersEditButton,0);
            gtk_widget_set_sensitive(widgets->BootUsersRemoveButton,0);
        }
    } else if (self == widgets->BootRingtoneTree){

        if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->BootRingtoneTree)),&model,&iter)) {
            int user_created;
            gtk_tree_model_get(model,&iter,3,&user_created,-1);
            if (user_created){
                gtk_widget_set_sensitive(widgets->BootRingtoneEditButton,1);
                gtk_widget_set_sensitive(widgets->BootRingtoneRemoveButton,1);
            } else {
                gtk_widget_set_sensitive(widgets->BootRingtoneEditButton,0);
                gtk_widget_set_sensitive(widgets->BootRingtoneRemoveButton,0);
            }
        } else {
            gtk_widget_set_sensitive(widgets->BootRingtoneEditButton,0);
            gtk_widget_set_sensitive(widgets->BootRingtoneRemoveButton,0);
        }
    }
}

void on_melody_toggled(GtkCellRenderer *, char *path, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->BootRingtoneList);
    GtkTreePath *cur_path = gtk_tree_path_new_from_string(path);

        for_iter(model,&iter){
            int status;
            gtk_tree_model_get(model,&iter,0,&status,-1);
            GtkTreePath *compare_path = gtk_tree_model_get_path(model,&iter);
            if (gtk_tree_path_compare(cur_path,compare_path)){
                gtk_list_store_set(widgets->BootRingtoneList,&iter,0,0,-1);
            } else {
                    gtk_list_store_set(widgets->BootRingtoneList,&iter,0,!status,-1);
                if (status){
                    yon_config_remove_by_key(GRUB_PLAY_parameter);
                } else {
                    char *code;
                    gtk_tree_model_get(model,&iter,2,&code,-1);
                    yon_config_register(GRUB_PLAY_parameter,GRUB_PLAY_command,(char*)code);

                }
            }
            gtk_tree_path_free(compare_path);
        }
        gtk_tree_path_free(cur_path);
}
// standard functions

/**config_init() 
 * [EN] 
 *  
 * [RU] 
 * Функция инициализации всех параметров конфигурации 
*/ 
void config_init(){ 
    main_config.always_open_documentation=0; 
    main_config.socket_id=-1; 
    main_config.save_socket_id=-1; 
    main_config.load_socket_id=-1; 
    main_config.lock_help=0; 
    main_config.lock_help=0; 
    main_config.lock_load_global=0; 
    main_config.lock_save_global=0; 
    main_config.lock_save_local=0; 
    main_config.load_mode=YON_CONFIG_LOCAL;
	main_config.password_min_length = yon_password_get_min_len();
    main_config.kernel_parameters = yon_resource_open_file(kernel_options_path,&main_config.kernel_size);
    main_config.input_parameters = yon_resource_open_file(terminal_input_path,&main_config.input_size);
    main_config.output_parameters = yon_resource_open_file(terminal_output_path,&main_config.output_size);
}

void on_parameter_changed(GtkWidget *self,main_window *widgets){
    if (self == widgets->BootSelectionTimerSpin||self == widgets->BootSelectionTimerCheck){
        if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->BootSelectionTimerCheck))){
            glong val = gtk_spin_button_get_value(GTK_SPIN_BUTTON(widgets->BootSelectionTimerSpin));
            if (val){
                yon_config_register(GRUB_TIMEOUT_parameter,GRUB_TIMEOUT_command,yon_char_from_long(val));
                return;
            }
        }
        yon_config_remove_by_key(GRUB_TIMEOUT_parameter);
    } else if (self == widgets->BootDisplayModeCombo){
        char *display_mode = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(widgets->BootDisplayModeCombo));
        if (!yon_char_is_empty(display_mode)){
            yon_config_register(GRUB_BOOT_SILENT_parameter,GRUB_BOOT_SILENT_command,display_mode);
        } else {
            yon_config_remove_by_key(GRUB_BOOT_SILENT_parameter);
        }
    }// else if (){
}

/**yon_main_window_complete(main_window *widgets) 
 * [EN] 
 *  
 * [RU] 
 * Функция настройки основного окна приложения. [widgets] - структура со стандартным интерфейсом. 
*/ 
void yon_main_window_complete(main_window *widgets){ 
    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); 
    // Custom widgets configuration 
    {
        widgets->BootDisplayModeCombo = yon_gtk_builder_get_widget(builder,"BootDisplayModeCombo");
        widgets->BootRingtoneAddButton = yon_gtk_builder_get_widget(builder,"BootRingtoneAddButton");
        widgets->BootRingtoneEditButton = yon_gtk_builder_get_widget(builder,"BootRingtoneEditButton");
        widgets->BootRingtoneRemoveButton = yon_gtk_builder_get_widget(builder,"BootRingtoneRemoveButton");
        widgets->BootRingtoneTree = yon_gtk_builder_get_widget(builder,"BootRingtoneTree");
        widgets->BootSelectionTimerCheck = yon_gtk_builder_get_widget(builder,"BootSelectionTimerCheck");
        widgets->BootSelectionTimerSpin = yon_gtk_builder_get_widget(builder,"BootSelectionTimerSpin");
        widgets->BootUsersAddButton = yon_gtk_builder_get_widget(builder,"BootUsersAddButton");
        widgets->BootUsersEditButton = yon_gtk_builder_get_widget(builder,"BootUsersEditButton");
        widgets->BootUsersRemoveButton = yon_gtk_builder_get_widget(builder,"BootUsersRemoveButton");
        widgets->BootUsersTree = yon_gtk_builder_get_widget(builder,"BootUsersTree");
        widgets->CommandLineParametersEntry = yon_gtk_builder_get_widget(builder,"CommandLineParametersEntry");
        widgets->InputTerminalEntry = yon_gtk_builder_get_widget(builder,"InputTerminalEntry");
        widgets->InputTerminalTree = yon_gtk_builder_get_widget(builder,"InputTerminalTree");
        widgets->KernelParametersTree = yon_gtk_builder_get_widget(builder,"KernelParametersTree");
        widgets->MenuButton = yon_gtk_builder_get_widget(builder,"MenuButton");
        widgets->MenuOverlay = yon_gtk_builder_get_widget(builder,"MenuOverlay");
        widgets->OSDefaultEntry = yon_gtk_builder_get_widget(builder,"OSDefaultEntry");
        widgets->OutputTerminalEntry = yon_gtk_builder_get_widget(builder,"OutputTerminalEntry");
        widgets->OutputTerminalTree = yon_gtk_builder_get_widget(builder,"OutputTerminalTree");
        widgets->KernelChooseCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"KernelChooseCell"));
        widgets->InputChosenCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"InputChosenCell"));
        widgets->OutputChosenCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"OutputChosenCell"));
        widgets->BootUsersList = GTK_LIST_STORE(gtk_builder_get_object(builder,"BootUsersList"));
        widgets->BootRingtoneList = GTK_LIST_STORE(gtk_builder_get_object(builder,"BootRingtoneList"));
        widgets->KernelParametersList = GTK_LIST_STORE(gtk_builder_get_object(builder,"KernelParametersList"));
        widgets->InputTerminalList = GTK_LIST_STORE(gtk_builder_get_object(builder,"InputTerminalList"));
        widgets->OutputTerminalList = GTK_LIST_STORE(gtk_builder_get_object(builder,"OutputTerminalList"));
        widgets->MelodyChosenCellRenderer = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"MelodyChosenCellRenderer"));

    }

    g_signal_connect(G_OBJECT(widgets->MenuButton),"clicked",G_CALLBACK(yon_menu_window_open),widgets);
    g_signal_connect(G_OBJECT(widgets->BootUsersAddButton),"clicked",G_CALLBACK(on_user_add_clicked),widgets);
    g_signal_connect(G_OBJECT(widgets->BootUsersEditButton),"clicked",G_CALLBACK(on_user_edit_clicked),widgets);
    g_signal_connect(G_OBJECT(widgets->BootUsersRemoveButton),"clicked",G_CALLBACK(on_user_remove_clicked),widgets);
    g_signal_connect(G_OBJECT(widgets->BootRingtoneAddButton),"clicked",G_CALLBACK(on_ringtone_add_clicked),widgets);
    g_signal_connect(G_OBJECT(widgets->BootRingtoneEditButton),"clicked",G_CALLBACK(on_ringtone_edit_clicked),widgets);
    g_signal_connect(G_OBJECT(widgets->BootRingtoneRemoveButton),"clicked",G_CALLBACK(on_ringtone_remove_clicked),widgets);

    g_signal_connect(G_OBJECT(widgets->MelodyChosenCellRenderer),"toggled",G_CALLBACK(on_melody_toggled),widgets);
    g_signal_connect(G_OBJECT(widgets->KernelChooseCell),"toggled",G_CALLBACK(on_kernel_parameter_switch),widgets);
    g_signal_connect(G_OBJECT(widgets->InputChosenCell),"toggled",G_CALLBACK(on_input_option_switch),widgets);
    g_signal_connect(G_OBJECT(widgets->OutputChosenCell),"toggled",G_CALLBACK(on_output_option_switch),widgets);

    g_signal_connect(G_OBJECT(widgets->BootSelectionTimerCheck),"toggled",G_CALLBACK(yon_gtk_widget_set_sensitive_from_toggle_button),widgets->BootSelectionTimerSpin);
    g_signal_connect(G_OBJECT(widgets->BootSelectionTimerCheck),"toggled",G_CALLBACK(on_parameter_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->BootSelectionTimerSpin),"changed",G_CALLBACK(on_parameter_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->BootDisplayModeCombo),"changed",G_CALLBACK(on_parameter_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->CommandLineParametersEntry),"changed",G_CALLBACK(on_parameter_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->InputTerminalEntry),"changed",G_CALLBACK(on_parameter_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->OutputTerminalEntry),"changed",G_CALLBACK(on_parameter_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->OSDefaultEntry),"changed",G_CALLBACK(on_parameter_changed),widgets);

    g_signal_connect(G_OBJECT(widgets->LoadLocalMenuItem),"activate",G_CALLBACK(on_config_local_load),widgets);
    g_signal_connect(G_OBJECT(widgets->LoadGlobalMenuItem),"activate",G_CALLBACK(on_config_global_load),widgets);
    g_signal_connect(G_OBJECT(widgets->LoadCustomMenuItem),"activate",G_CALLBACK(on_config_custom_load),widgets);

    g_signal_connect(G_OBJECT(widgets->SaveMenuItem),"activate",G_CALLBACK(on_config_global_local_save),NULL);
    g_signal_connect(G_OBJECT(widgets->SaveLocalMenuItem),"activate",G_CALLBACK(on_config_local_save),NULL);
    g_signal_connect(G_OBJECT(widgets->SaveGlobalMenuItem),"activate",G_CALLBACK(on_config_global_save),NULL);
    g_signal_connect(G_OBJECT(widgets->SaveCustomMenuItem),"activate",G_CALLBACK(on_config_custom_save),NULL);

    g_signal_connect(G_OBJECT(widgets->BootUsersTree),"cursor-changed",G_CALLBACK(on_tree_view_selection_changed),widgets);
    g_signal_connect(G_OBJECT(widgets->BootRingtoneTree),"cursor-changed",G_CALLBACK(on_tree_view_selection_changed),widgets);
    
    yon_root_button_setup((template_main_window*)widgets,main_config.launch_arguments,main_config.launch_size);
    yon_save_window_set_postsave_function(on_save_done,widgets);
    yon_load_proceed(YON_CONFIG_LOCAL);
    char *path = yon_char_unite(yon_ubl_user_get_home_directory(),"/.config/",LocaleName,"/",LocaleName,".conf",NULL);
    yon_window_config_load(path);
    yon_interface_update(widgets);
            bind_textdomain_codeset("ublinux-init-grub-functions","UTF-8");
}

int main(int argc, char *argv[]){ 
    setlocale(LC_ALL, "");
    textdomain (LocaleName);
    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(); 
    main_config.launch_arguments=yon_char_parsed_copy(argv,argc);
    main_config.launch_size=argc;
    yon_main_window_complete((main_window*)widgets);
    if (getuid()!=0){
        textdomain(template_ui_LocaleName);
        yon_ubl_status_box_render(ROOT_WARNING_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
        textdomain(LocaleName);
    }
    gtk_main();
    return 0;
}