#include "ubl-settings-repomanager.h"


// // storage-configure window section

void yon_storage_open_add_repos(char *storage_path, storage_config_window *window){
    int size;
    config_str repos = yon_file_list_dirs(storage_path,&size);

    storage_struct *storage = g_hash_table_lookup(window->storages_copy,storage_path);
    if (size){
        for (int i=0;i<size;i++){
            char *repo_name = repos[i];
            if (!strcmp(repo_name,"pool")) continue;
            if (g_hash_table_lookup(storage->repos,repo_name)){
                yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),ALREADY_EXIST_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
                yon_ubl_status_highlight_incorrect(window->AddEntry);
                continue;
            }
            char *new_repo = yon_char_new(repo_name);
            repo_struct *repo = yon_repo_struct_new();
            storage_repo_block *block = yon_storage_repo_block_new();
            g_object_set_data(G_OBJECT(block->SignatureCombo),"repo_storage",repo);
            g_object_set_data(G_OBJECT(block->SignatureCombo),"window",window);
            g_object_set_data(G_OBJECT(block->RepoRemoveButton),"window",window);
            repo->name=new_repo;
            block->repo_name=new_repo;
            repo->path = yon_char_unite(storage_path,"/",new_repo,NULL);
            repo->storage_path = yon_char_new(storage_path);
            yon_config_append_element(storage->path,(char*)repo->path,",");
            gtk_entry_set_text(GTK_ENTRY(block->RepoNameEntry),new_repo);
            gtk_box_pack_start(GTK_BOX(window->ReposBox),block->MainBox,0,0,0);
            g_hash_table_insert(storage->repos,repo->name,repo);
            // yon_storage_struct_add_repo(storage,repo);
            gtk_entry_set_text(GTK_ENTRY(window->AddEntry),"");
        }
    }
}

void on_storage_open(GtkWidget *self, storage_config_window *window){

    filechooser_window *dialog = yon_file_chooser_window_new(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
    yon_gtk_window_setup(GTK_WINDOW(dialog->Window),GTK_WINDOW(window->MainWindow),OPEN_STORAGE_TOOLTIP_LABEL,icon_path,"file_chooser_window");
    gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog->MainFileChooser),1);
    if (yon_char_is_empty(main_config.last_selection)){
        char *user_folder_path = yon_ubl_user_get_home_directory();
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog->MainFileChooser),user_folder_path);
    } else {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog->MainFileChooser),main_config.last_selection);
    }
    if (yon_file_chooser_start(dialog)==GTK_RESPONSE_ACCEPT){
        char *filename = dialog->last_success_selection;
        int exist_size=0;
        config_str exist_storages = (config_str)g_hash_table_get_keys_as_array(main_config.storages,&exist_size);
        for (int i=0;i<exist_size;i++){
        printf("%s  --  %s\n",filename,exist_storages[i]);
            if (strstr(filename,exist_storages[i])){
            yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),INSIDE_STORAGE_ERROR_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
            return;
            }
        }
        storage_struct *storage = yon_storage_struct_new();
        storage->path=dialog->last_success_selection;
        storage->name = yon_char_new(storage->path);
        if (!yon_char_is_empty(main_config.last_selection)) free(main_config.last_selection);
        main_config.last_selection = yon_char_new(storage->path);
        free(yon_char_divide(storage->name,yon_char_find_last(storage->name,'/')));
        g_hash_table_insert(window->storages_copy,storage->path,storage);
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->StoragePathCombo),storage->path,storage->path);
        while (gtk_events_pending()) gtk_main_iteration();
        gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->StoragePathCombo),storage->path);
        yon_config_register(storage->path,STORAGE_command,"");
        yon_storage_open_add_repos(storage->path,window);
        yon_storage_config_update(window);

    }
}

void on_storage_create(GtkWidget *self, storage_config_window *window){
    filechooser_window *dialog = yon_file_chooser_window_new(GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER);
    if (yon_char_is_empty(main_config.last_selection)){
        char *user_folder_path = yon_ubl_user_get_home_directory();
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog->MainFileChooser),user_folder_path);
    } else {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog->MainFileChooser),main_config.last_selection);
    }
    yon_gtk_window_setup(GTK_WINDOW(dialog->Window),GTK_WINDOW(window->MainWindow),CREATE_NEW_STORAGE_LABEL,icon_path,"file_chooser_window");
    gtk_button_set_label(GTK_BUTTON(dialog->SaveButton),yon_char_get_localised_from_lib(CREATE_NEW_TOOLTIP_LABEL));
    if (yon_file_chooser_start(dialog)==GTK_RESPONSE_APPLY){
        int exist_size=0;
        config_str exist_storages = (config_str)g_hash_table_get_keys_as_array(main_config.storages,&exist_size);
        for (int i=0;i<exist_size;i++){
            if (strstr(dialog->last_success_selection,exist_storages[i])){
            yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),INSIDE_STORAGE_ERROR_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
            return;
            }
        }

        storage_struct *storage = yon_storage_struct_new();
        yon_char_parsed_free(exist_storages,exist_size);
        storage->path=dialog->last_success_selection;
        storage->name = yon_char_new(storage->path);
        if (!yon_char_is_empty(main_config.last_selection)) free(main_config.last_selection);
        main_config.last_selection = yon_char_new(storage->path);
        free(yon_char_divide(storage->name,yon_char_find_last(storage->name,'/')));
        g_hash_table_insert(window->storages_copy,storage->path,storage);
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->StoragePathCombo),storage->path,storage->path);
        while (gtk_events_pending()) gtk_main_iteration();
        gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->StoragePathCombo),storage->path);
        yon_config_register(storage->path,STORAGE_command,"");
    }
}

void on_storage_disable(GtkWidget *self, storage_config_window *window){
    dialog_confirmation_data *data = yon_confirmation_dialog_data_new();
    data->title = DISABLE_TOOLTIP_LABEL;
    data->action_text = DISABLE_CONFIRMATION_LABEL;
    if (yon_confirmation_dialog_call(self,data)!=GTK_RESPONSE_ACCEPT){
        return;
    }
    const char *storage_target = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
    if (yon_char_is_empty(storage_target)) return;
    storage_struct *storage = g_hash_table_lookup(window->storages_copy,storage_target);
    if (storage){
        const char *path = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
        if (!config((char*)path)){
            yon_config_register((char*)path,STORAGE_command,"-");
        }
            yon_config_set_status((char*)path,-1);
        gtk_combo_box_text_remove(GTK_COMBO_BOX_TEXT(window->StoragePathCombo),gtk_combo_box_get_active(GTK_COMBO_BOX(window->StoragePathCombo)));
        gtk_combo_box_set_active(GTK_COMBO_BOX(window->StoragePathCombo),0);
        // g_hash_table_remove(window->storages_copy,storage_target);
        // yon_storage_sturct_free_full(storage);
    }
}

void on_storage_remove(GtkWidget *self, storage_config_window *window){
    dialog_confirmation_data *data = yon_confirmation_dialog_data_new();
    data->title = REMOVE_LABEL;
    data->action_text = REMOVE_CONFIRMATION_LABEL;
    if (yon_confirmation_dialog_call(self,data)!=GTK_RESPONSE_ACCEPT){
        return;
    }
    const char *storage_target = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
    if (yon_char_is_empty(storage_target)) return;
    storage_struct *storage = g_hash_table_lookup(window->storages_copy,storage_target);
    if (storage){
        const char *path = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
            yon_config_register((char*)path,STORAGE_command,"-");
            yon_config_set_status((char*)path,-2);
        gtk_combo_box_text_remove(GTK_COMBO_BOX_TEXT(window->StoragePathCombo),gtk_combo_box_get_active(GTK_COMBO_BOX(window->StoragePathCombo)));
        gtk_combo_box_set_active(GTK_COMBO_BOX(window->StoragePathCombo),0);
        // g_hash_table_remove(window->storages_copy,storage_target);
        // yon_storage_sturct_free_full(storage);
    }
}

void on_repo_add(GtkWidget *self, storage_config_window *window){
    const char *repo_name = gtk_entry_get_text(GTK_ENTRY(window->AddEntry));
    if (yon_char_is_empty(repo_name)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->AddEntry);
        return;
    }
    const char *storage_target = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
    storage_struct *storage = g_hash_table_lookup(window->storages_copy,storage_target);
    if (g_hash_table_lookup(storage->repos,repo_name)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),ALREADY_EXIST_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->AddEntry);
        return;
    }
    char *new_repo = yon_char_new(repo_name);
    repo_struct *repo = yon_repo_struct_new();
    storage_repo_block *block = yon_storage_repo_block_new();
    g_object_set_data(G_OBJECT(block->SignatureCombo),"repo_storage",repo);
    g_object_set_data(G_OBJECT(block->SignatureCombo),"window",window);
    g_object_set_data(G_OBJECT(block->RepoRemoveButton),"window",window);
    repo->name=new_repo;
    block->repo_name=new_repo;
    repo->path = yon_char_unite(storage_target,"/",new_repo,NULL);
    repo->storage_path = yon_char_new(storage_target);
    yon_config_append_element(storage->path,(char*)repo->path,",");
    gtk_entry_set_text(GTK_ENTRY(block->RepoNameEntry),new_repo);
    gtk_box_pack_start(GTK_BOX(window->ReposBox),block->MainBox,0,0,0);
    g_hash_table_insert(storage->repos,repo->name,repo);
    // yon_storage_struct_add_repo(storage,repo);
    gtk_entry_set_text(GTK_ENTRY(window->AddEntry),"");
}

void yon_storage_config_update(storage_config_window *window){
    GList *children = gtk_container_get_children(GTK_CONTAINER(window->ReposBox));
    if (children){
        GList *iter;
        for(iter=children;iter;iter=iter->next){
            gtk_widget_destroy(GTK_WIDGET(iter->data));
        }
    }
    const char *active = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
    if (active){
        storage_struct *storage = g_hash_table_lookup(window->storages_copy,active);
        int size;
            config_str repo_keys = (config_str)g_hash_table_get_keys_as_array(storage->repos,&size);
            qsort(repo_keys,size,sizeof(char*),(__compar_fn_t)yon_char_parsed_compare);
        for (int i = 0;i<size;i++){
            repo_struct *repos = g_hash_table_lookup(storage->repos,repo_keys[i]);
        if (repos){
                repo_struct *cur_repo = repos;
                storage_repo_block *cur_block = NULL;
                cur_block = yon_storage_repo_block_new();
                g_object_set_data(G_OBJECT(cur_block->SignatureCombo),"repo_storage",cur_repo);
                g_object_set_data(G_OBJECT(cur_block->SignatureCombo),"window",window);
                g_object_set_data(G_OBJECT(cur_block->RepoRemoveButton),"window",window);
                cur_block->repo_name=yon_char_new(cur_repo->name);
                gtk_entry_set_text(GTK_ENTRY(cur_block->RepoNameEntry),cur_repo->name);
                gtk_box_pack_start(GTK_BOX(window->ReposBox),cur_block->MainBox,0,0,0);
            }
        }
    }
}

void yon_storage_remove(char *key, storage_struct *storage,void*){
    char *parameter = config(key);
    switch (yon_config_get_status(key)){
        case -2: yon_window_config_erase_instant_parameter(key,"storage_info");
            if (rmdir(key)){};
        break;
        case -1: yon_window_config_erase_instant_parameter(key,"storage_info");
        break;
        case 0:
        break;
        case 1: yon_window_config_add_instant_parameter(key,"storage_info",parameter,YON_TYPE_STRING);
        break;
    }
    int size;
    if (!yon_char_is_empty(parameter)&&strcmp(parameter,"-")){
    config_str parsed = yon_char_parse(parameter,&size,",");
        for (int i=0;i<size;i++){
            char *sign = config(parsed[i]);
            char *repo_name = parsed[i]+yon_char_find_last(parsed[i],'/')+1;
            char *command = create_storage_command(key,repo_name,sign);
            yon_launch(yon_debug_output("%s\n\n",command));
            free(command);
        }
    }
    yon_storage_sturct_free_full(storage);
}



void on_storage_accept(GtkWidget *self, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    storage_config_window *window = yon_dictionary_get_data(dict->first->next,storage_config_window*);
    if (!yon_char_is_empty(gtk_entry_get_text(GTK_ENTRY(window->AddEntry)))){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),UNADDED_REPO_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->AddRepoButton);
        return;
    }
    gtk_widget_destroy(window->MainWindow);
    int size;
    config_str keys = (config_str)g_hash_table_get_keys_as_array(window->storages_copy,&size);
    for (int i=0;i<size;i++){
            int repos_size;
            config_str repos = yon_char_parse(config(keys[i]),&repos_size,",");
            if (repos_size){
                qsort(repos,repos_size,sizeof(char*),(__compar_fn_t)yon_char_parsed_compare);
                char *repos_string = yon_char_parsed_to_string(repos,repos_size,",");
                int config_status = yon_config_get_status(keys[i]);
                yon_config_set(keys[i],repos_string);
                yon_config_set_status(keys[i],config_status);
                free(repos_string);
                yon_char_parsed_free(repos,repos_size);
            }
        yon_storage_remove(keys[i],g_hash_table_lookup(window->storages_copy,keys[i]),NULL);
    }
    g_hash_table_remove_all(window->storages_copy);
    // g_hash_table_foreach_remove(window->storages_copy,(GHRFunc)yon_storage_remove,NULL);
    g_hash_table_unref(window->storages_copy);
    free(window);
    yon_interface_update(widgets); 
}

void on_storage_changed(GtkWidget *self, storage_config_window *window){
    yon_storage_config_update(window);
}

void yon_repo_creation_set_sensitive_from_combo_box(GtkComboBox *toggle, GtkWidget *target){
    gtk_widget_set_sensitive(target,gtk_combo_box_get_active(toggle)>-1 ? 1 : 0);
}

storage_config_window *yon_storage_config_window_new(){
    storage_config_window *window = malloc(sizeof(storage_config_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_storage_config);
    window->MainWindow = yon_gtk_builder_get_widget(builder,"MainWindow");
    window->HeadLabel = yon_gtk_builder_get_widget(builder,"HeadLabel");
    window->CancelButton = yon_gtk_builder_get_widget(builder,"CancelButton");
    window->AcceptButton = yon_gtk_builder_get_widget(builder,"AcceptButton");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->StoragePathCombo = yon_gtk_builder_get_widget(builder,"StoragePathCombo");
    window->OpenExistingButton = yon_gtk_builder_get_widget(builder,"OpenExistingButton");
    window->CreateNewButton = yon_gtk_builder_get_widget(builder,"CreateNewButton");
    window->DisableButton = yon_gtk_builder_get_widget(builder,"DisableButton");
    window->DeleteButton = yon_gtk_builder_get_widget(builder,"DeleteButton");
    window->ReposBox = yon_gtk_builder_get_widget(builder,"ReposBox");
    window->AddEntry = yon_gtk_builder_get_widget(builder,"AddEntry");
    window->AddRepoButton = yon_gtk_builder_get_widget(builder,"AddRepoButton");
    window->storages_copy = g_hash_table_new(g_str_hash,g_str_equal);
    window->delete_storages=NULL;
    window->delete_storages_size=0;

    yon_storage_hash_table_clone(main_config.storages,window->storages_copy);

    GList *list = g_hash_table_get_values(window->storages_copy);
    GList *iter;
    for (iter=list;iter;iter=iter->next){
        storage_struct *storage = (storage_struct*)iter->data;
        int repos_size;
        config_str paths = NULL;
        GList *repos = g_hash_table_get_values(storage->repos);
        GList *iter2;
        for (iter2=repos;iter2;iter2=iter2->next){
            repo_struct *repo = (repo_struct*)iter2->data;
            yon_char_parsed_add_or_create_if_exists(paths,&repos_size,repo->path);
        }
        qsort(paths,repos_size,sizeof(char*),(__compar_fn_t)yon_char_parsed_compare);
        yon_config_register(storage->path,STORAGE_command,yon_char_parsed_to_string(paths,repos_size,","));
    }
    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
    g_signal_connect(G_OBJECT(window->OpenExistingButton),"clicked",G_CALLBACK(on_storage_open),window);
    g_signal_connect(G_OBJECT(window->CreateNewButton),"clicked",G_CALLBACK(on_storage_create),window);
    g_signal_connect(G_OBJECT(window->DisableButton),"clicked",G_CALLBACK(on_storage_disable),window);
    g_signal_connect(G_OBJECT(window->DeleteButton),"clicked",G_CALLBACK(on_storage_remove),window);
    g_signal_connect(G_OBJECT(window->AddRepoButton),"clicked",G_CALLBACK(on_repo_add),window);
    g_signal_connect(G_OBJECT(window->StoragePathCombo),"changed",G_CALLBACK(on_storage_changed),window);
    g_signal_connect(G_OBJECT(window->StoragePathCombo),"changed",G_CALLBACK(yon_repo_creation_set_sensitive_from_combo_box),window->AddEntry);
    g_signal_connect(G_OBJECT(window->StoragePathCombo),"changed",G_CALLBACK(yon_repo_creation_set_sensitive_from_combo_box),window->AddRepoButton);
    

    return window;
}

void on_storage_configure_clicked(GtkWidget *self, main_window *widgets){
    storage_config_window *window = yon_storage_config_window_new();
    yon_gtk_window_setup(GTK_WINDOW(window->MainWindow),GTK_WINDOW(widgets->Window),MANAGE_STORAGES_TITLE_LABEL,icon_path,"storage-configuration-window");
    GtkTreeIter iter,itar;
    GList *storages = g_hash_table_get_values(main_config.storages);
    GList *listiter;
    for (listiter = storages;listiter;listiter=listiter->next){
        storage_struct *cur_storage = (storage_struct*)listiter->data;
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->StoragePathCombo),cur_storage->path,cur_storage->path);
    }
    dictionary *dict = NULL;
    yon_dictionary_add_or_create_if_exists_with_data(dict,"widgets",widgets);
    yon_dictionary_add_or_create_if_exists_with_data(dict,"window",window);
    g_signal_connect(G_OBJECT(window->AcceptButton),"clicked",G_CALLBACK(on_storage_accept),dict);
    gtk_widget_show(window->MainWindow);
}
