#include "ubinstall-gtk.h"

void yon_config_save_proceed(char *path, YON_CONFIG_TYPE type){
        yon_debug_output("%s\n",yon_config_save_simple(type,path));
}

void yon_load_proceed(YON_CONFIG_TYPE type){
	if (type!=YON_CONFIG_CUSTOM){
		yon_config_clean();
        if (main_config.config_load_path&&!main_config.configure_mode){
            if (main_config.startup_config){
                yon_config_restore(NULL);
                yon_config_custom_clean(main_config.startup_config);
            }
            main_config.startup_config = NULL;
        }
	}
    if (!yon_char_is_empty(config_get_default_command)){
        yon_config_load_config(YON_CONFIG_DEFAULT,config_get_default_command,NULL);
    }
    switch (type){
        case YON_CONFIG_LOCAL:
            main_config.config_load_path = yon_char_new("system");
            main_config.config_save_path = main_config.config_load_path;
            if (!main_config.configure_mode){
                yon_config_custom_load_config(&main_config.startup_config,config_get_command("system"),NULL);
            }
            yon_config_load_config(type,config_get_command("system"),NULL);
            break;
        case YON_CONFIG_CUSTOM:
            if (yon_char_is_empty(main_config.force_ini)){
                char *path = NULL;
                path=yon_custom_config_init(GTK_FILE_CHOOSER_ACTION_OPEN);
                if (!yon_char_is_empty(path)){
                    if (main_config.config_load_path&&!main_config.configure_mode){
                        if (main_config.startup_config){
                            yon_config_restore(NULL);
                            yon_config_custom_clean(main_config.startup_config);
                        }
                        main_config.startup_config = NULL;
                    }
                    main_config.config_load_path = yon_char_new(path);
                    main_config.config_save_path = main_config.config_load_path;
                    yon_config_clean();
                    yon_config_load_config(type,config_get_command(path),NULL);
                    if (!main_config.configure_mode){
                        yon_config_custom_load_config(&main_config.startup_config,config_get_command(path),NULL);
                    }
                }
            } else {
                yon_config_clean();
                yon_config_load_config(type,config_get_command(main_config.force_ini),NULL);
                if (!main_config.configure_mode){
                    yon_config_custom_load_config(&main_config.startup_config,config_get_command(main_config.force_ini),NULL);
                }
            }
            break;
        default:
            break;
    }
}

void on_config_local_load(GtkWidget *,main_window *widgets){
    if (!yon_char_is_empty(main_config.force_ini)) {
        on_config_custom_load_last(NULL,widgets);
        return;
    }
    yon_load_proceed(YON_CONFIG_LOCAL);
    main_config.load_mode=YON_CONFIG_LOCAL;
    yon_main_window_update_locale(widgets);
    yon_navigation_buttons_set_sensetiveness(widgets);
}

void on_config_custom_load(GtkWidget *,main_window *widgets){
    char *temp_custom_path = NULL;
	yon_load_proceed(YON_CONFIG_CUSTOM);
    if (!yon_char_is_empty(main_config.config_load_path)){
        main_config.load_mode=YON_CONFIG_CUSTOM;
        free(temp_custom_path);
    }
    yon_navigation_buttons_set_sensetiveness(widgets);
}

void on_config_custom_load_last(GtkWidget *,main_window *widgets){
    yon_config_clean();
    if (!yon_char_is_empty(config_get_default_command))
        yon_config_load_config(YON_CONFIG_DEFAULT,config_get_default_command,NULL);
    char *command = config_get_command(main_config.config_load_path);
    yon_config_load_config(YON_CONFIG_CUSTOM,command,NULL);
	main_config.load_mode=YON_CONFIG_CUSTOM;
    int page = gtk_notebook_get_current_page(GTK_NOTEBOOK(widgets->Notebook));
    yon_page_init(widgets,page);
}

void on_config_global_local_save(GtkWidget *,main_window *widgets){
    yon_config_save_proceed(NULL,YON_CONFIG_BOTH);
    gtk_notebook_set_current_page(GTK_NOTEBOOK(widgets->Notebook),YON_PAGE_COMPLETED);
}

void on_config_local_save(GtkWidget *,main_window *widgets){
    yon_config_save_proceed("system",YON_CONFIG_LOCAL);
    gtk_notebook_set_current_page(GTK_NOTEBOOK(widgets->Notebook),YON_PAGE_COMPLETED);

}

void on_config_global_save(GtkWidget *,main_window *widgets){
    yon_config_save_proceed("global",YON_CONFIG_GLOBAL);
    gtk_notebook_set_current_page(GTK_NOTEBOOK(widgets->Notebook),YON_PAGE_COMPLETED);

}

gboolean on_install_success(main_window *widgets){
    gtk_label_set_text(GTK_LABEL(widgets->InstallationLabel),"");
    on_page_next_clicked(NULL,widgets);

    return 0;
}

gboolean on_install_error(main_window *widgets){
    gtk_label_set_text(GTK_LABEL(widgets->InstallationLabel),"");
    gtk_notebook_set_current_page(GTK_NOTEBOOK(widgets->Notebook),YON_PAGE_INSTALL_ERROR);
    yon_page_update(widgets);

    return 0;
}

enum INSTALL_TYPE{
    INSTALL_COMMON,
    INSTALL_PART,
    INSTALL_NEXT,
    INSTALL_ADVANCED,
    INSTALL_GRUB_INSTALL,
    INSTALL_GRUB_UPDATE,
    INSTALL_SYSTEM_ONLY,
    INSTALL_USER_ONLY,
    INSTALL_ERROR
};

/**Функция получения текущего режима установки
 * 
 */
enum INSTALL_TYPE yon_ubl_get_install_mode(){
    
    char *value = config(AUTOINSTALL_TYPE_INSTALL);
    if (!yon_char_is_empty(value)){
        if (!strcmp(value,"fast")){
            return INSTALL_COMMON;
        } else if (!strcmp(value,"part")){
            return INSTALL_PART;
        } else if (!strcmp(value,"next")){
            return INSTALL_NEXT;
        } else if (!strcmp(value,"advanced")){
            return INSTALL_ADVANCED;
        } else if (!strcmp(value,"grub_install")){
            return INSTALL_GRUB_INSTALL;
        } else if (!strcmp(value,"grub_update")){
            return INSTALL_GRUB_UPDATE;
        } else if (!strcmp(value,"system_only")){
            return INSTALL_SYSTEM_ONLY;
        } else if (!strcmp(value,"data_only")){
            return INSTALL_USER_ONLY;
        }
    }
    return INSTALL_ERROR;
}

void on_config_install_success(GtkWidget *, int state, main_window *widgets){
    if (state){
        gdk_threads_add_idle((GSourceFunc)on_install_error,widgets);
        g_mutex_lock(&main_config.install_mutex);
        main_config.install_complete=1;
        g_mutex_unlock(&main_config.install_mutex);
        return;
    }
    g_mutex_lock(&main_config.install_mutex);
    if (!main_config.install_complete){
        main_config.install_complete = 1;
    }
    g_mutex_unlock(&main_config.install_mutex);
    if ((!main_config.save_done)&&main_config.save_configured){
        on_setup_system_configuration(widgets);
    } else if (main_config.save_done&&main_config.save_configured){
        g_idle_add((GSourceFunc)on_install_success,widgets);

    } else {
        main_config.save_done=1;
    }
}

void *on_config_save(void *data){
    main_window *widgets = (main_window*)data;

        g_idle_add((GSourceFunc)yon_progress_bar_start,widgets);
        char *command = yon_debug_output("%s\n",install_start_command(main_config.config_save_path));
        if (!main_config.dry_run){
            yon_debug_output("%s\n","Entered installation");
            if (system(command)){

                gdk_threads_add_idle((GSourceFunc)on_install_error,widgets);
                free(command);
                g_mutex_lock(&main_config.install_mutex);
                main_config.install_complete=1;
                g_mutex_unlock(&main_config.install_mutex);
                return 0;
            };
            free(command);
            g_mutex_lock(&main_config.install_mutex);
            main_config.install_complete=1;
            g_mutex_unlock(&main_config.install_mutex);
            if ((!main_config.save_done)&&main_config.save_configured){
                on_setup_system_configuration(widgets);
            }
        } else {
            yon_launch("ubconfig --source system get /");
        }
    return 0;
}

void *on_setup_system_configuration(void * data){
    yon_debug_output("%s\n","Entered thread");
    main_window *widgets = (main_window*)data;
    if (widgets){};
        
            char *command = yon_debug_output("%s\n",configuration_start_command(main_config.config_save_path));
        if (!main_config.dry_run){
            if (system(command)){};
            free(command);
        } else {
            yon_launch("ubconfig --source system get /");
            yon_launch(ubinstall_dry_run_command);
        }
    // }
    g_idle_add((GSourceFunc)on_install_success,widgets);
    return NULL;
}

int yon_config_save(main_window *widgets){
    {
        int size=0;
        config_str parameters = NULL;
        enum INSTALL_TYPE install_mode = yon_ubl_get_install_mode();
        switch(install_mode){
            case INSTALL_COMMON:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_common_parameters,modules_parameter,NULL);
            break;
            case INSTALL_PART:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_part_parameters,modules_parameter,NULL);
            break;
            case INSTALL_NEXT:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_next_parameters,modules_parameter,NULL);
            break;
            case INSTALL_ADVANCED:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_advanced_parameters,modules_parameter,NULL);
            break;
            case INSTALL_GRUB_INSTALL:
            case INSTALL_GRUB_UPDATE:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_grub_install_update_parameters,NULL);
            break;
            case INSTALL_SYSTEM_ONLY:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_system_only_parameters,NULL);
            break;
            case INSTALL_USER_ONLY:
                parameters = yon_config_get_selection_by_key_no_ignored(&size,install_userdata_only_parameters,NULL);
            break;
            default:
                yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),ERROR_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE); 
                return 0;
        }
        char *command = yon_debug_output("%s\n",ubconfig_set_command_full(main_config.config_load_path,"[autoinstall]",yon_char_parsed_to_string(parameters,size," ")));
        if (system(command)){
            return 0;
        }
    }
    int size;
    config_str all_parameters = yon_config_get_selection_by_key(&size,
    root_password_parameter,
    autologin_parameter,
    xkbmodel_parameter,
    xkblayout_parameter,
    xkbvariant_parameter,
    xkboptions_parameter,
    hostname_parameter,
    zone_parameter,
    lang_parameter,
    locale_parameter,
    SERVICES_ENABLE_parameter,
    GRUB_DEFAULT_parameter,
    GRUB_TIMEOUT_parameter,
    GRUB_SUPERUSERS_parameter,
    DOMAIN_parameter,
    DOMAIN_admanger_parameter,
    NTPSERVERS_parameter,
    packages_parameter,
    KERNEL_BOOT_parameter,
    packages_parameter,
    NULL);
    int user_size=0;
    config_str users = yon_config_get_all_by_key(USERADD_parameter_search,&user_size);
    if (user_size){
        int final_size;
        config_str final = yon_char_parsed_merge(all_parameters,size,users,user_size,&final_size);
        yon_char_parsed_free(users,user_size);
        if (size) yon_char_parsed_free(all_parameters,size);
        all_parameters = final;
        size = final_size;
    }
    users = yon_config_get_all_by_key(GRUB_PASSWORD_parameter_search,&user_size);
    if (users){
        int final_size;
        config_str final = yon_char_parsed_merge(all_parameters,size,users,user_size,&final_size);
        yon_char_parsed_free(users,user_size);
        if (size) yon_char_parsed_free(all_parameters,size);
        all_parameters = final;
        size = final_size;
    }
    int network_size;
    config_str networks = yon_config_get_all_by_key(NETWORK_parameter_search,&network_size);
    if (network_size){
        int final_size;
        config_str final = yon_char_parsed_merge(all_parameters,size,networks,network_size,&final_size);
        yon_char_parsed_free(networks,network_size);
        if (size) yon_char_parsed_free(all_parameters,size);
        all_parameters = final;
        size = final_size;
    }

    if (all_parameters){
        for (int i=0;i<size;i++){
            char *parameter = yon_char_divide_search(all_parameters[i],"=",-1);
            if (!strstr(parameter,"'")){
                char *key = yon_config_parameter_get_key(parameter);
                free(parameter);
                char *tmp = yon_char_unite("'",key,"'",NULL);
                free(key);
                parameter = AUTOINSTALL(tmp);
                free(tmp);
            }
            if (!strstr(all_parameters[i],"'")){
                char *temp = yon_char_unite("'",all_parameters[i],"'",NULL);
                free(all_parameters[i]);
                all_parameters[i]=temp;
            }
            char *temp = yon_char_unite(parameter,"=",all_parameters[i],NULL);
            free(all_parameters[i]);
            all_parameters[i]=temp;

            
        }
        char *parameter_string = yon_char_parsed_to_string(all_parameters,size," ");
        if (!yon_char_is_empty(parameter_string)){
            char *command = ubconfig_set_command_full(main_config.config_save_path,"",parameter_string);
            if (!system(command)){
                return 1;
            } else return 0;
            
        }
    }
    return 1;
}

void yon_config_restore(main_window *){
    if (yon_char_is_empty(main_config.config_load_path)||!main_config.block_restore) return;
    char *remove_command = yon_char_unite("ubconfig --source ",main_config.config_load_path," remove [autoinstall]",NULL);
    yon_launch(yon_debug_output("%s\n",remove_command));
    yon_config_custom_apply(&main_config.startup_config);
    yon_config_set_status_full(1);
    int size = 0;
    config_str parameters = yon_config_get_save_parameters(&size);
    if (size){
        char *command_params = yon_char_parsed_to_string(parameters,size, " ");
        char *command = yon_char_unite(ubconfig_set_command(main_config.config_load_path),command_params,NULL);
        yon_debug_output("%s\n",command);
        yon_launch(command);
        yon_char_parsed_free(parameters,size);
        free(command);
    }
}