#include "ubinstall-gtk.h"

int yon_install_common_save(main_window *widgets){
    GtkTreeModel *model;
    GtkTreeIter iter;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->CommonInstallationDevicesTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->CommonInstallationDevicesTree));
        return 0;
    }
    char *device;
    yon_config_remove_by_key(part_size_parameter);
    yon_config_remove_by_key(part_parameter);
    gtk_tree_model_get(model,&iter,0,&device,-1);
    yon_config_register(AUTOINSTALL_TYPE_INSTALL,AUTOINSTALL_TYPE_INSTALL_command,"fast");
    yon_config_register(AUTOINSTALL_DEVICE,AUTOINSTALL_DEVICE_command,device);

    char *device_name = (char*)gtk_entry_get_text(GTK_ENTRY(widgets->CommonInstallationSectionNameEntry));
    if (!yon_char_is_empty(device_name)){
        yon_config_register(part_label_parameter,part_label_parameter_command,device_name);
    } else {
        yon_config_remove_by_key(part_label_parameter);
    }

    char *file_system_type = (char*)gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(widgets->CommonInstallationFilesystemTypeCombo));
    if (!yon_char_is_empty(file_system_type)){
        yon_config_register(part_fs_type_parameter,part_fs_type_parameter_command,file_system_type);
    } else {
        yon_config_remove_by_key(part_fs_type_parameter);
    }

    if (!main_config.configure_mode){
        int size;
        config_str parameters = yon_config_get_save_parameters_by_key(&size,AUTOINSTALL_TYPE_INSTALL,AUTOINSTALL_DEVICE,part_label_parameter,part_fs_type_parameter,NULL);
        if (parameters){
            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)){}
            free(command);
            yon_char_parsed_free(parameters,size);
        }
    }
    return 1;
}

int yon_install_separate_save(main_window *widgets){
    GtkTreeModel *model;
    GtkTreeIter iter;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->NextInstallationSysDevicesTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->CommonInstallationDevicesTree));
        return 0;
    }
    char *device;
    gtk_tree_model_get(model,&iter,0,&device,-1);
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->NextInstallationSysSectionTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->CommonInstallationDevicesTree));
        return 0;
    }
    if (gtk_switch_get_active(GTK_SWITCH(widgets->NextInstallationFormatSwitch))){
        yon_config_register(part_format_parameter,part_format_parameter_command,"yes");
        double part_size = gtk_spin_button_get_value(GTK_SPIN_BUTTON(widgets->NextInstallationSizeSpin));
        if (part_size){
            char *size_letter = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(widgets->NextInstallationSizeTypeSpin));
            char *size_final = yon_char_append(yon_char_from_long((long)part_size),size_letter);
            yon_config_register(part_size_parameter,part_size_parameter_command,size_final);
        } else {
            yon_config_remove_by_key(part_size_parameter);
        }

            char *device_name = (char*)gtk_entry_get_text(GTK_ENTRY(widgets->NextInstallationSectionNameEntry));
        if (!yon_char_is_empty(device_name)){
            yon_config_register(part_label_parameter,part_label_parameter_command,device_name);
        } else {
            yon_config_remove_by_key(part_label_parameter);

        }

        char *file_system_type = (char*)gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(widgets->NextInstallationFilesystemTypeCombo));
        if (!yon_char_is_empty(file_system_type)){
            yon_config_register(part_fs_type_parameter,part_fs_type_parameter_command,file_system_type);

        } else {
            yon_config_remove_by_key(part_fs_type_parameter);

        }
    } else {
            yon_config_register(part_format_parameter,part_format_parameter_command,"no");
            yon_config_remove_by_key(part_label_parameter);
            yon_config_remove_by_key(part_fs_type_parameter);
            yon_config_remove_by_key(part_format_parameter);
            yon_config_remove_by_key(part_fs_type_parameter);
            yon_config_remove_by_key(part_format_parameter);
    }
    
    char *part;
    gtk_tree_model_get(model,&iter,0,&part,-1);
    yon_config_register(AUTOINSTALL_TYPE_INSTALL,AUTOINSTALL_TYPE_INSTALL_command,"next");
    yon_config_register(AUTOINSTALL_DEVICE,AUTOINSTALL_DEVICE_command,device);
    yon_config_register(part_parameter,part_parameter_command,part);
    if (!main_config.configure_mode){
        int size;
        config_str parameters = yon_config_get_save_parameters_by_key(&size,part_format_parameter,part_label_parameter,part_fs_type_parameter,AUTOINSTALL_DEVICE,part_parameter,NULL);
        if (parameters){
            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)){}
            free(command);
            yon_char_parsed_free(parameters,size);
        }
    }
    return 1;
}

int yon_install_same_partition_save(main_window *widgets){
    GtkTreeModel *model;
    GtkTreeIter iter;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->SamePlaceDeviceTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->CommonInstallationDevicesTree));
        return 0;
    }
    char *device;
    gtk_tree_model_get(model,&iter,0,&device,-1);
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->SamePlacePartTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->CommonInstallationDevicesTree));
        return 0;
    }
    yon_config_remove_by_key(part_size_parameter);
    char *part;
    gtk_tree_model_get(model,&iter,0,&part,-1);
        yon_config_register(AUTOINSTALL_TYPE_INSTALL,AUTOINSTALL_TYPE_INSTALL_command,"part");
        yon_config_register(AUTOINSTALL_DEVICE,AUTOINSTALL_DEVICE_command,device);
        yon_config_register(part_parameter,part_parameter_command,part);

    if (gtk_switch_get_active(GTK_SWITCH(widgets->SameInstallationFormatSwitch))){
        yon_config_register(part_format_parameter,part_format_parameter_command,"yes");
        char *device_name = (char*)gtk_entry_get_text(GTK_ENTRY(widgets->SameInstallationSectionNameEntry));
        if (!yon_char_is_empty(device_name)){
            yon_config_register(part_label_parameter,part_label_parameter_command,device_name);
        } else {
            yon_config_remove_by_key(part_label_parameter);
        }

        char *file_system_type = (char*)gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(widgets->SameInstallationFilesystemTypeCombo));
        if (!yon_char_is_empty(file_system_type)){
            yon_config_register(part_fs_type_parameter,part_fs_type_parameter_command,file_system_type);
        } else {
            yon_config_remove_by_key(part_fs_type_parameter);

        }
    } else {
        yon_config_register(part_format_parameter,part_format_parameter_command,"no");
        yon_config_remove_by_key(part_label_parameter);
        yon_config_remove_by_key(part_format_parameter);
        yon_config_remove_by_key(part_fs_type_parameter);
    }
    if (!main_config.configure_mode){
        int size;
        config_str parameters = yon_config_get_save_parameters_by_key(&size,part_format_parameter,part_size_parameter,part_label_parameter,part_fs_type_parameter,AUTOINSTALL_TYPE_INSTALL,AUTOINSTALL_DEVICE,part_parameter,NULL);
        if (parameters){
            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)){}
            free(command);
            yon_char_parsed_free(parameters,size);
        }
    }
    return 1;
}

int yon_advanced_sections_save(dictionary *dict){
    if (!dict) return 0;
    advanced_partition *first_section = yon_dictionary_get_data(dict->first,advanced_partition*);
    advanced_partition *last_section = NULL;
    if (dict->first->next){
        last_section = yon_dictionary_get_data(dict->first->next,advanced_partition*);
    }

    char *part_first = first_section->part;
    char *part_last = last_section?last_section->part:NULL;
    char *part = yon_char_unite(part_first,last_section?",":NULL,part_last,NULL);
    yon_config_register(part_parameter,part_parameter_command,part);

    char * format_first = gtk_switch_get_active(GTK_SWITCH(first_section->FormatSwitch))?"yes":"no";
    char * format_last = last_section?gtk_switch_get_active(GTK_SWITCH(last_section->FormatSwitch))?"yes":"no":NULL;
    char *format = yon_char_unite(format_first,part_last?",":NULL,format_last,NULL);
    yon_config_register(part_format_parameter,part_format_parameter_command,format);

    if (!yon_char_is_empty(format)){
        char *size_first = g_strdup_printf("%d%s",gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(first_section->SizeSpin)),yon_size_get_mod(gtk_combo_box_get_active(GTK_COMBO_BOX(first_section->SizeCombo))));
        char *size_last = last_section&&!strcmp(format_last,"yes")?g_strdup_printf("%d%s",gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(last_section->SizeSpin)),yon_size_get_mod(gtk_combo_box_get_active(GTK_COMBO_BOX(last_section->SizeCombo)))):NULL;
        char *size = yon_char_unite(size_first,size_last?",":NULL,size_last,NULL);
        yon_config_register(part_size_parameter,part_size_parameter_command,size);
        
        char *part_label_first = (char*)gtk_entry_get_text(GTK_ENTRY(first_section->SectionMarkEntry));
        char *part_label_last = last_section&&!strcmp(format_last,"yes")?(char*)gtk_entry_get_text(GTK_ENTRY(last_section->SectionMarkEntry)):NULL;
        char *part_label = yon_char_unite(part_label_first,part_label_last?",":NULL,part_label_last,NULL);
        yon_config_register(part_label_parameter,part_label_parameter_command,part_label);

        char *fs_label_first = (char*)gtk_entry_get_text(GTK_ENTRY(first_section->FileSystemMarkentry));
        char *fs_label_last = last_section&&!strcmp(format_last,"yes")?(char*)gtk_entry_get_text(GTK_ENTRY(last_section->FileSystemMarkentry)):NULL;
        char *fs_label = yon_char_unite(fs_label_first,fs_label_last?",":NULL,fs_label_last,NULL);
        yon_config_register(part_fs_label_parameter,part_fs_label_parameter_command,fs_label);

        char *fs_type_first = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(first_section->FileSystemTypeCombo));
        char *fs_type_last = last_section&&!strcmp(format_last,"yes")?(char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(last_section->FileSystemTypeCombo)):NULL;
        char *fs_type = yon_char_unite(fs_type_first,fs_type_last?",":NULL,fs_type_last,NULL);
        yon_config_register(part_fs_type_parameter,part_fs_type_parameter_command,fs_type);

        char *part_crypt_first = gtk_combo_box_get_active(GTK_COMBO_BOX(first_section->EncryptionCombo))?(char*)gtk_entry_get_text(GTK_ENTRY(first_section->EncryptionEntry)):NULL;
        char *part_crypt_last = last_section&&!strcmp(format_last,"yes")&&gtk_combo_box_get_active(GTK_COMBO_BOX(last_section->EncryptionCombo))?(char*)gtk_entry_get_text(GTK_ENTRY(first_section->EncryptionEntry)):NULL;
        char *part_crypt = NULL;
        if (part_crypt_first||part_crypt_last){
            part_crypt = yon_char_unite(part_crypt_first,part_crypt_last?",":NULL,part_crypt_last,NULL);
        }
        if (part_crypt){
            yon_config_register(part_crypt_parameter,part_crypt_parameter_command,part_crypt);
        } else {
            yon_config_remove_by_key(part_crypt_parameter);
        }
    }
    return 1;
}

int yon_install_advanced_save(main_window *widgets){

    GtkTreeModel *model;
    GtkTreeIter iter;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->AdvancedDeviceTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->AdvancedDeviceTree));
        return 0;
    }
    char *device;
    gtk_tree_model_get(model,&iter,0,&device,-1);
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->AdvancedPartitionTree)),&model,&iter)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),NO_DEVICE_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(gtk_widget_get_parent(widgets->AdvancedPartitionTree));
        return 0;
    }
    yon_config_remove_by_key(part_size_parameter);
    char *part;
    gtk_tree_model_get(model,&iter,0,&part,-1);

    if (!yon_advanced_sections_save(widgets->advanced_sections)){
        return 0;
    }

    if (gtk_switch_get_active(GTK_SWITCH(widgets->AdvancedSwapSwitch))){
        if (gtk_switch_get_active(GTK_SWITCH(widgets->AdvancedSwapAutoSwitch))){
            yon_config_register(swap_parameter,swap_parameter_command,"auto");
        } else if (gtk_switch_get_active(GTK_SWITCH(widgets->AdvancedSwapRamSwitch))){
            yon_config_register(swap_parameter,swap_parameter_command,"yes");
            yon_config_register(swap_size_parameter,swap_size_parameter_command,"ram");
        } else {
            yon_config_register(swap_parameter,swap_parameter_command,"yes");
            char *swap = g_strdup_printf("%d%s",gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(widgets->AdvancedSwapFixedSpin)),yon_size_get_mod(gtk_combo_box_get_active(GTK_COMBO_BOX(widgets->AdvancedSwapFixedSizeSwitch))+1));
            yon_config_register(swap_size_parameter,swap_size_parameter_command,swap);
        }
    }
    const char *device_typevfs = gtk_combo_box_get_active_id(GTK_COMBO_BOX(widgets->AdvancedVirtualDeviceCombo));
    if (!yon_char_is_empty(device_typevfs)){
        yon_config_register(device_typevfs_parameter,device_typevfs_parameter_command,(char*)device_typevfs);
    } else {
        yon_config_remove_by_key(device_typevfs_parameter);
    }
    if (gtk_switch_get_active(GTK_SWITCH(widgets->AdvancedLoadTypeSwitch))){
        char *bios = gtk_switch_get_active(GTK_SWITCH(widgets->AdvancedBiosSectorSwitch))?"bios":"";
        char *efi = gtk_switch_get_active(GTK_SWITCH(widgets->AdvancedEFISwitch))?"efi":NULL;
        char *boot = yon_char_unite(bios,!yon_char_is_empty(bios)&&!yon_char_is_empty(efi)?"+":"",efi,NULL);
        yon_config_register(boot_parameter,boot_parameter_command,boot);
    } else {
        yon_config_register(boot_parameter,boot_parameter_command,"none");
    }

    return 1;
}

void yon_install_advanced_init(main_window *){
    // char *boot = config(boot_parameter);
    // char *swap = config(swap_parameter);
}

void yon_set_max_size_from_partition(GtkTreeView *table, GtkSpinButton *spin_button, GtkComboBox *spin_combo){
    GtkTreeModel *model;
    GtkTreeIter iter;
    long selected_size;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(table),&model,&iter)){
        gtk_tree_model_get(model,&iter,6,&selected_size,-1);
        if (!selected_size){
            gtk_tree_model_get(model,&iter,5,&selected_size,-1);
        }
        if (selected_size){
            GtkAdjustment *adj = gtk_spin_button_get_adjustment(spin_button);
            const char *sizemod = gtk_combo_box_get_active_id(spin_combo);
            double new_size = yon_size_long_convert_to_mod(selected_size,sizemod[0]);
            gtk_adjustment_set_upper(adj,new_size);
            gdouble old_value = gtk_adjustment_get_value(adj);
            if (old_value>new_size){
                gtk_adjustment_set_value(adj,new_size);
            }
        }
    }
}

void on_partition_changed(GtkWidget *self, main_window *widgets){
    if (self==widgets->NextInstallationSysSectionTree||self == widgets->NextInstallationSizeTypeSpin){
        yon_set_max_size_from_partition(GTK_TREE_VIEW(widgets->NextInstallationSysSectionTree),GTK_SPIN_BUTTON(widgets->NextInstallationSizeSpin),GTK_COMBO_BOX(widgets->NextInstallationSizeTypeSpin));
    }

}

void on_device_selection_changed(GtkWidget *self, main_window *widgets){
    gtk_list_store_clear(widgets->PartitionsList);
    GtkTreeIter iter;
    GtkTreeModel *model;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(self)),&model,&iter)){
        char *disk_path;
        gtk_tree_model_get(model,&iter,0,&disk_path,-1);
        int size;
        config_str partitions;
        partitions = yon_config_load(yon_debug_output("%s\n",get_parts_and_devices_command),&size);
        for (int i=0;i<size;i++){
            yon_char_remove_last_symbol(partitions[i],'\n');
            int parsed_size;
            config_str parsed = yon_char_parse(partitions[i],&parsed_size,";");
            if (!strcmp(parsed[0],"part")){
                char *name = parsed[1];
                if (strstr(name,disk_path)){
                    char *capacity = NULL;
                    long capacity_long = 0;
                    char *free_space = NULL;
                    long free_space_long = 0;
                    char *fs_type = NULL;
                    char *label = NULL;

                    if (parsed_size>2){
                        char sizemod='\0';
                        capacity_long = atol(parsed[2]);
                        
                        char *temp = yon_char_from_double(yon_size_long_convert_automatic(capacity_long,&sizemod));
                        capacity = yon_char_append_c(temp,sizemod);
                        free(temp);
                    }
                    if (parsed_size>7&&!yon_char_is_empty(parsed[7])){
                        char sizemod='\0';
                        free_space_long = capacity_long-atol(parsed[7]);
                        char *temp = yon_char_from_double(yon_size_long_convert_automatic(free_space_long,&sizemod));
                        free_space = yon_char_append_c(temp,sizemod);
                        free(temp);
                    }
                    if (parsed_size>3){
                        fs_type = parsed[3];
                    }
                    if (parsed_size>4){
                        label = parsed[4];
                    }

                    gtk_list_store_append(widgets->PartitionsList,&iter);
                    gtk_list_store_set(widgets->PartitionsList,&iter,0,name,1,capacity,2,free_space,3,fs_type,4,label,5,capacity_long,6,free_space_long,-1);
                }
                yon_char_parsed_free(parsed,parsed_size);
            }
        }
        gtk_spin_button_set_value(GTK_SPIN_BUTTON(widgets->NextInstallationSizeSpin),0.0);
        gtk_adjustment_set_upper(gtk_spin_button_get_adjustment(GTK_SPIN_BUTTON(widgets->NextInstallationSizeSpin)),0.0);
    }
}

void yon_devices_setup(main_window *widgets){
    GtkTreeIter iter;
    if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(widgets->DevicesList),&iter)) return;
    int size;
    config_str parsed = NULL;
    parsed = yon_config_load(yon_debug_output("%s\n",get_devices_command),&size);
    char *string = yon_char_parsed_to_string(parsed,size,"");
    struct json_object *root;
    struct json_object *blockdevices;
    root = json_tokener_parse(string);
    free(string);
    json_object_object_get_ex(root, "blockdevices", &blockdevices);
    for (long unsigned int i = 0; i < json_object_array_length(blockdevices); i++) {
        struct json_object *device = json_object_array_get_idx(blockdevices, i);
        struct json_object *path, *size, *model, *vendor, *serial;

        json_object_object_get_ex(device, "path", &path);
        json_object_object_get_ex(device, "size", &size);
        json_object_object_get_ex(device, "model", &model);
        json_object_object_get_ex(device, "vendor", &vendor);
        json_object_object_get_ex(device, "serial", &serial);

        gtk_list_store_append(widgets->DevicesList,&iter);
        gtk_list_store_set(widgets->DevicesList,&iter,0,json_object_get_string(path),1,json_object_get_string(model),2,json_object_get_string(serial),3,json_object_get_string(size),4,json_object_get_string(vendor),6,1,-1);
        
    }
    yon_char_parsed_free(parsed,size);
}

void yon_install_init(main_window *widgets, enum YON_PAGES page){
    yon_devices_setup(widgets);
    
    GtkWidget *device_tree = NULL;
    GtkWidget *partition_tree = NULL;
    GtkWidget *format_switch = NULL;
    GtkWidget *device_label = NULL;
    GtkWidget *fs_type_combo = NULL;
    GtkWidget *partition_size_spin = NULL;
    GtkWidget *partition_size_combo = NULL;
    GtkWidget *partition_mark_entry = NULL;
    GtkWidget *partition_fs_mark_entry = NULL;
    GtkWidget *partition_encryption_combo = NULL;
    GtkWidget *partition_encryption_entry = NULL;

    switch(page){
        case YON_PAGE_INSTALL_COMMON:
            device_tree = widgets->CommonInstallationDevicesTree;
            device_label = widgets->CommonInstallationSectionNameEntry;
            format_switch = widgets->CommonFormatSwitch;
            fs_type_combo = widgets->CommonInstallationFilesystemTypeCombo;
        break;
        case YON_PAGE_INSTALL_SAME_PARTITION:
            device_tree = widgets->SamePlaceDeviceTree;
            partition_tree = widgets->SamePlacePartTree;
            format_switch = widgets->SameInstallationFormatSwitch;
            partition_mark_entry = widgets->SameInstallationSectionNameEntry;
            fs_type_combo = widgets->SameInstallationFilesystemTypeCombo;
        break;
        case YON_PAGE_INSTALL_SEPARATE:
            device_tree = widgets->NextInstallationSysDevicesTree;
            partition_tree = widgets->NextInstallationSysSectionTree;
            format_switch = widgets->NextInstallationFormatSwitch;
            partition_size_spin = widgets->NextInstallationSizeSpin;
            partition_size_combo = widgets->NextInstallationSizeTypeSpin;
            partition_mark_entry = widgets->NextInstallationSectionNameEntry;
            fs_type_combo = widgets->NextInstallationFilesystemTypeCombo;

        break;
        case YON_PAGE_INSTALL_ADVANCED:
            yon_install_advanced_init(widgets);
            return;
        break;
        case YON_PAGE_RECOVERY_GRUB_INSTALL:
            device_tree = widgets->GrubInstallDevicesTree;
            partition_tree = widgets->GrubInstallPartitionTree;

        break;
        case YON_PAGE_RECOVERY_GRUB_UPDATE:
            device_tree = widgets->GrubUpdateDevicesTree;
            partition_tree = widgets->GrubUpdatePartitionTree;

        break;
        case YON_PAGE_RECOVERY_OS_ONLY:
            device_tree = widgets->OSDevicesTree;
            partition_tree = widgets->OSSysSectionTree;
            format_switch = widgets->OSFormatSwitch;
            partition_size_spin = widgets->OSFormatSizeSpin;
            partition_size_combo = widgets->OSFormatSizeCombo;
            partition_mark_entry = widgets->OSFormatPartitionEntry;
            fs_type_combo = widgets->OSFilesystemTypeCombo;
            partition_fs_mark_entry = widgets->OSFormatFSMarkEntry;
            partition_encryption_combo = widgets->OSFormatEncryptionCombo;
            partition_encryption_entry = widgets->OSFormatEncryptionEntry;

        break;
        case YON_PAGE_RECOVERY_USRDATA_ONLY:
            device_tree = widgets->UserdataDevicesTree;
            partition_tree = widgets->UserdataSysSectionTree;
            format_switch = widgets->OSFormatSwitch;
            partition_size_spin = widgets->UserdataFormatSwitch;
            partition_size_combo = widgets->UserdataFormatSizeCombo;
            partition_mark_entry = widgets->UserdataFormatPartitionEntry;
            fs_type_combo = widgets->UserdataFilesystemTypeCombo;
            partition_fs_mark_entry = widgets->UserdataFormatFSMarkEntry;
            partition_encryption_combo = widgets->UserdataFormatEncryptionCombo;
            partition_encryption_entry = widgets->UserdataFormatEncryptionEntry;
        break;
        default:return;
    }

    char *device = config(AUTOINSTALL_DEVICE);
    char *part = config(part_parameter);

    if (!yon_char_is_empty(device)){
        GtkTreeIter iter;
        GtkTreeModel *model = GTK_TREE_MODEL(widgets->DevicesList);
        for_iter(model,&iter){
            char *target;
            gtk_tree_model_get(model,&iter,0,&target,-1);
            if (!yon_char_is_empty(target)&&!strcmp(target,device)){
                gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(device_tree)),&iter);
                break;
            }
        }
        if (partition_tree&&!yon_char_is_empty(part)){
            model = GTK_TREE_MODEL(widgets->PartitionsList);
            for_iter(model,&iter){
                char *target;
                gtk_tree_model_get(model,&iter,0,&target,-1);
                if (!yon_char_is_empty(target)&&!strcmp(target,device)){
                    gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(partition_tree)),&iter);
                    break;
                }
            }
        }
    }
    if (format_switch){
        char *format = config(part_format_parameter);
        if ((!yon_char_is_empty(format)&&!strcmp(format,"yes"))||format_switch==widgets->CommonFormatSwitch){
            gtk_switch_set_active(GTK_SWITCH(format_switch),1);
            if (device_label){
                char *parameter = config(part_label_parameter);
                if (!yon_char_is_empty(parameter)){
                    gtk_entry_set_text(GTK_ENTRY(device_label),parameter);
                } else {
                    gtk_entry_set_text(GTK_ENTRY(device_label),"");
                }
            }
            if (fs_type_combo){
                gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(fs_type_combo));
                int size;
                config_str fs_types = yon_resource_open_file(fs_types_path,&size);
                for (int i=0;i<size;i++){
                    int parsed_size;
                    config_str parsed = yon_char_parse(fs_types[i],&parsed_size,";");
                    if (atoi(parsed[0])){
                        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(fs_type_combo),parsed[1],parsed[1]);
                    }
                    yon_char_parsed_free(parsed,parsed_size);
                }
                    yon_char_parsed_free(fs_types,size);
                char *parameter = config(part_fs_type_parameter);
                if (!yon_char_is_empty(parameter)){
                    gtk_combo_box_set_active_id(GTK_COMBO_BOX(fs_type_combo),parameter);
                } else {
                    gtk_combo_box_set_active(GTK_COMBO_BOX(fs_type_combo),0);
                }
            }
            if (partition_size_spin&&partition_size_combo){
                char *parameter = config(part_size_parameter);
                if (!yon_char_is_empty(parameter)){
                    gtk_spin_button_set_value(GTK_SPIN_BUTTON(partition_size_spin),atol(parameter));
                    gtk_combo_box_set_active(GTK_COMBO_BOX(partition_size_combo),yon_get_size_get_from_letter(parameter[strlen(parameter)-1]));
                } else {
                    gtk_spin_button_set_value(GTK_SPIN_BUTTON(partition_size_spin),0);
                    gtk_combo_box_set_active(GTK_COMBO_BOX(partition_size_combo),0);
                }
            }
            if (partition_mark_entry){
                char *parameter = config(part_label_parameter);
                if (!yon_char_is_empty(parameter)){
                    gtk_entry_set_text(GTK_ENTRY(partition_mark_entry),parameter);
                } else {
                    gtk_entry_set_text(GTK_ENTRY(partition_mark_entry),"");
                }
            }
            if (partition_fs_mark_entry){
                char *parameter = config(part_fs_label_parameter);
                if (!yon_char_is_empty(parameter)){
                    gtk_entry_set_text(GTK_ENTRY(partition_fs_mark_entry),parameter);
                } else {
                    gtk_entry_set_text(GTK_ENTRY(partition_fs_mark_entry),"");
                }
            }
            if (partition_encryption_combo && partition_encryption_entry){
                char *parameter = config(part_crypt_parameter);
                if (!yon_char_is_empty(parameter)&&!strstr(parameter,",")){
                    char *password = yon_char_new(parameter);
                    char *crypt = yon_char_divide_search(password,":",-1);
                    gtk_combo_box_set_active_id(GTK_COMBO_BOX(partition_encryption_combo),crypt);
                    gtk_entry_set_text(GTK_ENTRY(partition_encryption_entry),password);
                    free(password);
                    free(crypt);
                } else {
                    gtk_combo_box_set_active(GTK_COMBO_BOX(partition_encryption_combo),0);
                    gtk_entry_set_text(GTK_ENTRY(partition_encryption_entry),"");
                }
            }
        } else {
            gtk_switch_set_active(GTK_SWITCH(format_switch),0);
        }
    }

}

void on_advanced_password_clicked(GtkWidget *, advanced_partition *part){
    yon_password_open(GTK_ENTRY(part->EncryptionEntry));
}

void yon_advanced_partition_clear(main_window *widgets){
    GList *list = gtk_container_get_children(GTK_CONTAINER(widgets->AdvancedPartitionAddBox));
    GList *iter;
    for (iter=list;iter;iter=iter->next){
        advanced_partition *part = g_object_get_data(G_OBJECT(iter->data),"advanced_partition");
        gtk_widget_destroy(GTK_WIDGET(iter->data));
        free(part);
    }
    on_advanced_parts_removed(NULL,NULL,widgets);
}

int yon_advanced_get_part_size(main_window *widgets){
    int size = 0;
    GList *list = gtk_container_get_children(GTK_CONTAINER(widgets->AdvancedPartitionAddBox));
    size = g_list_length(list);
    g_list_free(list);
    return size;
}

void yon_advanced_set_part_sensitivity(main_window *widgets, gboolean state){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->PartitionsList);
    int status;
    for_iter(model,&iter){
        gtk_tree_model_get(model,&iter,8,&status,-1);
        if (!status){
            gtk_list_store_set(widgets->PartitionsList,&iter,8,state?state:0,-1);
        } else {
            gtk_list_store_set(widgets->PartitionsList,&iter,8,1,-1);
        }
    }
}

void yon_advanced_set_device_sensitivity(main_window *widgets, gboolean state){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->DevicesList);
    for_iter(model,&iter){
        gtk_list_store_set(widgets->DevicesList,&iter,6,state,-1);
    }
}

advanced_partition *yon_advanced_partition_new(){
    advanced_partition *part = new(advanced_partition);
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_advanced_part);
    part->MainBox = yon_gtk_builder_get_widget(builder,"MainBox");
    part->SectionLabel = yon_gtk_builder_get_widget(builder,"SectionLabel");
    part->SystemSectionToggle = yon_gtk_builder_get_widget(builder,"SystemSectionToggle");
    part->UserDataSectionToggle = yon_gtk_builder_get_widget(builder,"UserDataSectionToggle");
    part->RemoveButton = yon_gtk_builder_get_widget(builder,"RemoveButton");
    part->FormatSwitch = yon_gtk_builder_get_widget(builder,"FormatSwitch");
    part->SizeSpin = yon_gtk_builder_get_widget(builder,"SizeSpin");
    part->SizeCombo = yon_gtk_builder_get_widget(builder,"SizeCombo");
    part->SectionMarkEntry = yon_gtk_builder_get_widget(builder,"SectionMarkEntry");
    part->FileSystemTypeCombo = yon_gtk_builder_get_widget(builder,"FileSystemTypeCombo");
    part->FileSystemMarkentry = yon_gtk_builder_get_widget(builder,"FileSystemMarkentry");
    part->EncryptionCombo = yon_gtk_builder_get_widget(builder,"EncryptionCombo");
    part->EncryptionEntry = yon_gtk_builder_get_widget(builder,"EncryptionEntry");
    part->EncryptionButton = yon_gtk_builder_get_widget(builder,"EncryptionButton");
    part->FormatRevealer = yon_gtk_builder_get_widget(builder,"FormatRevealer");
    part->order_iter = NULL;
    part->part = NULL;

    yon_gtk_revealer_set_from_switch(GTK_REVEALER(part->FormatRevealer),GTK_SWITCH(part->FormatSwitch));
    g_signal_connect(G_OBJECT(part->EncryptionButton),"clicked",G_CALLBACK(on_advanced_password_clicked),part);
    // g_signal_connect(G_OBJECT(part->SystemSectionToggle),"clicked",G_CALLBACK(on_advanced_system_toggled),part);
    // g_signal_connect(G_OBJECT(part->UserDataSectionToggle),"clicked",G_CALLBACK(on_advanced_user_toggled),part);

    g_object_set_data(G_OBJECT(part->MainBox),"advanced_partition",part);
    g_object_set_data(G_OBJECT(part->RemoveButton),"advanced_partition",part);

    return part;
}

void on_advanced_part_remove(GtkWidget *self, main_window *widgets){
    advanced_partition *part = g_object_get_data(G_OBJECT(self),"advanced_partition");

    if (part->part_type == ADVANCED_PART_EXISTING){
        GtkTreeIter iter;
        GtkTreeModel *model = GTK_TREE_MODEL(widgets->PartitionsList);
        for_iter(model,&iter){
            int status;
            char *target;
            gtk_tree_model_get(model,&iter,0,&target,7,&status,-1);
            if (status&&!strcmp(target,part->part)){
                gtk_list_store_set(GTK_LIST_STORE(model),&iter,7,0,-1);
                yon_advanced_set_part_sensitivity(widgets,1);
            }
            
        }
    }
    g_object_set_data(G_OBJECT(widgets->AdvancedPartitionAddBox),part->part,NULL);
    g_sequence_remove(part->order_iter);
    gtk_widget_destroy(part->MainBox);
    on_advanced_parts_removed(NULL,NULL,widgets);
    free(part);

}

void on_advanced_parts_added(GtkWidget *,GtkWidget*,main_window *widgets){
    if (yon_advanced_get_part_size(widgets)>=2){
        yon_advanced_set_part_sensitivity(widgets,0);
        gtk_widget_hide(widgets->AdvancedAddButton);
    }
}

void on_advanced_parts_removed(GtkWidget *,GtkWidget*,main_window *widgets){
    int size = yon_advanced_get_part_size(widgets);
    if (size<2){
        yon_advanced_set_part_sensitivity(widgets,1);
        gtk_widget_show(widgets->AdvancedAddButton);
    }
    if (!size){

    }
}

void yon_advanced_partition_setup(advanced_partition *part,main_window *widgets){
    g_signal_connect(G_OBJECT(part->RemoveButton),"clicked",G_CALLBACK(on_advanced_part_remove),widgets);
    g_object_set_data(G_OBJECT(widgets->AdvancedPartitionAddBox),part->part,part);
}

void on_install_advanced_add_new(GtkWidget *, main_window *widgets){
    advanced_partition *part = yon_advanced_partition_new();
    part->part_type = ADVANCED_PART_NEW;
    part->order_iter = g_sequence_append(widgets->advanced_partition_order,part);
    gtk_box_pack_start(GTK_BOX(widgets->AdvancedPartitionAddBox),part->MainBox,0,0,0);
    gtk_widget_show(part->MainBox);
    yon_advanced_partition_setup(part,widgets);
    on_advanced_parts_added(NULL,NULL,widgets);
}

void on_install_advanced_device_chosen(GtkCellRenderer *, gchar *path, main_window *widgets){
    gtk_list_store_clear(widgets->PartitionsList);
    yon_advanced_partition_clear(widgets);

    int size;
    config_str partitions;
    partitions = yon_config_load(yon_debug_output("%s\n",get_parts_and_devices_command),&size);
    for (int i=0;i<size;i++){
        yon_char_remove_last_symbol(partitions[i],'\n');
    }

    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->DevicesList);

    int chosen = 0;
    chosen = yon_advanced_get_part_size(widgets);
    
    if (gtk_tree_model_get_iter_from_string(model,&iter,path)){
        int status;
        gtk_tree_model_get(model,&iter,5,&status,-1);
        if (!status){
            if (chosen <2){
                gtk_list_store_set(widgets->DevicesList,&iter,5,!status,-1);
                chosen++;
            } else {
                for_iter (model,&iter){
                    gtk_tree_model_get(model,&iter,5,&status,-1);
                    if (!status){
                        gtk_list_store_set(widgets->DevicesList,&iter,6,0,-1);
                    }
                }

            }
        } else {
            gtk_list_store_set(widgets->DevicesList,&iter,5,!status,-1);
            if (chosen == 2){
                for_iter (model,&iter){
                        gtk_list_store_set(widgets->DevicesList,&iter,6,1,-1);
                }
            }
            chosen--;
        }
    }

    if (chosen) gtk_widget_set_sensitive(widgets->AdvancedAddButton,1);
    else gtk_widget_set_sensitive(widgets->AdvancedAddButton,0);
    
    for_iter (model,&iter){
        char *disk_path;
        int status;
        gtk_tree_model_get(model,&iter,0,&disk_path,5,&status,-1);
        if (!status) continue;

        for (int i=0;i<size;i++){
            int parsed_size;
            config_str parsed = yon_char_parse(partitions[i],&parsed_size,";");
            if (!strcmp(parsed[0],"part")){
                char *name = parsed[1];
                if (strstr(name,disk_path)){
                    char *capacity = NULL;
                    long capacity_long = 0;
                    char *free_space = NULL;
                    long free_space_long = 0;
                    char *fs_type = NULL;
                    char *label = NULL;

                    if (parsed_size>2){
                        char sizemod='\0';
                        capacity_long = atol(parsed[2]);
                        
                        char *temp = yon_char_from_double(yon_size_long_convert_automatic(capacity_long,&sizemod));
                        capacity = yon_char_append_c(temp,sizemod);
                        free(temp);
                    }
                    if (parsed_size>7&&!yon_char_is_empty(parsed[7])){
                        char sizemod='\0';
                        free_space_long = capacity_long-atol(parsed[7]);
                        char *temp = yon_char_from_double(yon_size_long_convert_automatic(free_space_long,&sizemod));
                        free_space = yon_char_append_c(temp,sizemod);
                        free(temp);
                    }
                    if (parsed_size>3){
                        fs_type = parsed[3];
                    }
                    if (parsed_size>4){
                        label = parsed[4];
                    }

                    GtkTreeIter itar;
                    gtk_list_store_append(widgets->PartitionsList,&itar);
                    gtk_list_store_set(widgets->PartitionsList,&itar,0,name,1,capacity,2,free_space,3,fs_type,4,label,5,capacity_long,6,free_space_long,8,1,-1);
                }
                yon_char_parsed_free(parsed,parsed_size);
            }
        }
    }
    
}

void on_install_advanced_partition_chosen(GtkCellRenderer*, gchar *path, main_window *widgets){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->PartitionsList);

    int chosen = 0;
    chosen = yon_advanced_get_part_size(widgets);

    gtk_tree_model_get_iter_from_string(model,&iter,path);
    int status;
    char *target_part;
    gtk_tree_model_get(model,&iter,0,&target_part,7,&status,-1);
    
    if (!status){
        if (chosen<2){
            gtk_list_store_set(widgets->PartitionsList,&iter,7,!status,-1);
            chosen++;
            advanced_partition *part = yon_advanced_partition_new();
            part->part_type = ADVANCED_PART_EXISTING;
            part->order_iter = g_sequence_append(widgets->advanced_partition_order,part);
            part->part = target_part;
            gtk_box_pack_start(GTK_BOX(widgets->AdvancedPartitionAddBox),part->MainBox,0,0,0);
            gtk_widget_show(part->MainBox);
            yon_advanced_partition_setup(part,widgets);
            on_advanced_parts_added(NULL,NULL,widgets);
        }
    } else {
        gtk_list_store_set(widgets->PartitionsList,&iter,7,!status,-1);
        advanced_partition *part = g_object_get_data(G_OBJECT(widgets->AdvancedPartitionAddBox),target_part);
        if (part){
            on_advanced_part_remove(part->RemoveButton,widgets);
        }
    }
}