#include "ubl-settings-repomanager.h"



void on_move_storage_changed(GtkWidget *self, repo_add_window *window){
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(window->MoveTargetRepoEntry));
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(window->MoveSourceRepoEntry));
    char *path_str = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceStorageEntry));
    if (!yon_char_is_empty(path_str)){
        gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->MoveTargetStorageEntry),path_str);
        storage_struct *storage = g_hash_table_lookup(main_config.storages,path_str);
        int size;
        config_str repos = (config_str)g_hash_table_get_keys_as_array(storage->repos,&size);
        for (int i=0;i<size;i++){
            gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->MoveSourceRepoEntry),repos[i],repos[i]);
            gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->MoveTargetRepoEntry),repos[i],repos[i]);
        }
    }
}

void on_move_repo_changed(GtkWidget *self, repo_add_window *window){
    if (gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceArchEntry))) return;
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(window->MoveTargetArchEntry));
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(window->MoveSourceArchEntry));
    GtkWidget *check_repo = NULL;
    if (self == window->MoveSourceRepoEntry){
        check_repo = window->MoveTargetRepoEntry;
    } else {
        check_repo = window->MoveSourceRepoEntry;
    }
    const char *current_repo_selection = gtk_combo_box_get_active_id(GTK_COMBO_BOX(self));
    const char *check_repo_selection = gtk_combo_box_get_active_id(GTK_COMBO_BOX(check_repo));
    if (!yon_char_is_empty(current_repo_selection)&&!yon_char_is_empty(check_repo_selection)&&!strcmp(current_repo_selection,check_repo_selection)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),REPO_SAME_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        return;
    }
    const char *storage_path = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceStorageEntry));
    const char *repo_name = gtk_combo_box_get_active_id(GTK_COMBO_BOX(self));
    if (yon_char_is_empty(storage_path)||yon_char_is_empty(repo_name)) return;
    storage_struct *storage = g_hash_table_lookup(main_config.storages,storage_path);
    if (storage){
        repo_struct *repo = g_hash_table_lookup(storage->repos,repo_name);
        if (repo){
            gtk_widget_set_sensitive(window->RepoSignCombo,1);
            int size;
            config_str archs = (config_str)g_hash_table_get_keys_as_array(repo->archs,&size);
            for (int i=0;i<size;i++){
                gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->MoveSourceArchEntry),archs[i],archs[i]);
                gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->MoveTargetArchEntry),archs[i],archs[i]);
            }
        }
    }
    if (!yon_char_is_empty(current_repo_selection)||!yon_char_is_empty(check_repo_selection)){
        gtk_widget_set_sensitive(window->MoveSourceArchEntry,1);
        gtk_widget_set_sensitive(window->MoveTargetArchEntry,1);
    } else {    
        gtk_widget_set_sensitive(window->MoveSourceArchEntry,0);
        gtk_widget_set_sensitive(window->MoveTargetArchEntry,0);
    }
    
}

void on_move_check_fill(GtkWidget *self, repo_add_window *window){
    if (gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceStorageEntry))&&
        gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceRepoEntry))&&
        gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceArchEntry))&&
        gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveTargetStorageEntry))&&
        gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveTargetRepoEntry))&&
        gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveTargetArchEntry))){
            gtk_widget_set_sensitive(window->AddPackageButton,1);
        }
}

void on_move_arch_changed(GtkWidget *self, repo_add_window *window){
    GtkWidget *check_arch = NULL;
    if (self == window->MoveSourceArchEntry){
        check_arch = window->MoveTargetArchEntry;
    } else {
        check_arch = window->MoveSourceArchEntry;
    }
    const char *chosen = gtk_combo_box_get_active_id(GTK_COMBO_BOX(self));
    if (!gtk_combo_box_set_active_id(GTK_COMBO_BOX(check_arch),chosen)){
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(check_arch),chosen,chosen);
        while(gtk_events_pending())gtk_main_iteration();
        gtk_combo_box_set_active_id(GTK_COMBO_BOX(check_arch),chosen);
    }
            gtk_widget_set_sensitive(window->MoveTargetArchEntry,0);
}

void on_move_add_accept(GtkWidget *self, dictionary *dict){
    repo_add_window *window = yon_dictionary_get_data(dict->first,repo_add_window*);
    filechooser_window *dialog = yon_dictionary_get_data(dict->first->next,filechooser_window*);

    int size;
    config_str packages = yon_char_parse(dialog->last_success_selection,&size,",");
    for (int i=0;i<size;i++){
        if (yon_file_is_directory(packages[i])){
            int dir_size;
            config_str files = yon_file_ls(packages[i],&dir_size);
            for (int k=0;k<dir_size;k++){
                if (strstr(files[k],".pkg.tar")&&!strstr(files[k],".sig")){
                    GtkTreeIter iter;
                    int temp_size;
                    char *full_path = yon_char_unite(packages[i],"/",files[k],NULL);
                    config_str name = yon_config_load(yon_get_package_name_from_filename(full_path),&temp_size);
                    if (name&&!yon_char_is_empty(name[0]))
                        yon_char_remove_last_symbol(name[0],'\n');
                    gtk_list_store_append(window->PackagesList,&iter);
                    gtk_list_store_set(window->PackagesList,&iter,1,name&&!yon_char_is_empty(name[0])?name[0]:"",2,full_path,-1);
                    free(full_path);
                }
            }

        } else {
            GtkTreeIter iter;
            int temp_size;
            config_str name = yon_config_load(yon_get_package_name_from_filename(packages[i]),&temp_size);
            if (temp_size<=0){
                yon_ubl_status_box_spawn(GTK_CONTAINER(dialog->StatusBox),PACKAGE_NAME_ERROR_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
                return;
            }
            yon_char_remove_last_symbol(name[0],'\n');
            if (!yon_gtk_tree_model_check_exist(GTK_TREE_MODEL(window->PackagesList),&iter,name[0],1)){
                gtk_list_store_append(window->PackagesList,&iter);
                gtk_list_store_set(window->PackagesList,&iter,1,name[0],2,packages[i],-1);
            } else {
                yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),ALREADY_EXIST_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
            }

        }
    }
    yon_char_parsed_free(packages,size);
    gtk_widget_destroy(dialog->Window);
    free(dialog);
    GtkTreeIter iter;
    if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(window->PackagesList),&iter)){
        gtk_widget_set_sensitive(window->MoveSourceStorageEntry,0);
        gtk_widget_set_sensitive(window->MoveSourceRepoEntry,0);
        gtk_widget_set_sensitive(window->MoveSourceArchEntry,0);

        gtk_widget_set_sensitive(window->MoveTargetRepoEntry,0);
        gtk_widget_set_sensitive(window->MoveTargetArchEntry,0);

        if (window->StorageCombo&&window->RepositoryCombo&&window->ArchitectureCombo){
            gtk_widget_set_sensitive(window->StorageCombo,0);
            gtk_widget_set_sensitive(window->RepositoryCombo,0);
            gtk_widget_set_sensitive(window->ArchitectureCombo,0);
        }
    }
}

void on_move_add_package(GtkWidget *self, repo_add_window *window){
    if (gtk_combo_box_get_active(GTK_COMBO_BOX(window->MoveTargetArchEntry))>-1&&gtk_combo_box_get_active(GTK_COMBO_BOX(window->MoveSourceStorageEntry))>-1){
        filechooser_window *dialog = yon_file_chooser_window_new(GTK_FILE_CHOOSER_ACTION_OPEN);
        yon_gtk_window_setup(GTK_WINDOW(dialog->Window),GTK_WINDOW(window->MainWindow),CHOSE_PACKAGES_TITLE_LABEL,icon_path,"ChooseMoveFileChooserWindow");
        gtk_label_set_text(GTK_LABEL(dialog->HeaderTopic),CHOSE_PACKAGES_TITLE_LABEL);
        GtkFileFilter *filter = gtk_file_filter_new();
        gtk_file_filter_add_pattern(filter,"*.pkg.tar*[^.sig]");
        gtk_file_filter_set_name(filter,"*.pkg.tar.*");
        gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog->MainFileChooser),filter);
        GtkTreeIter iter,itar;
        char *target;
        const char* storage_path = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceStorageEntry));
        storage_struct *storage = g_hash_table_lookup(main_config.storages,storage_path);
        if (storage){
            const char *repo_name = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceRepoEntry));
            repo_struct *repo = g_hash_table_lookup(storage->repos,repo_name);
            if (repo){
                target = repo->path;
            }
            gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog->MainFileChooser),1);
            gtk_widget_show(dialog->ChooseFolderCheck);

        }
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog->MainFileChooser),target);

            dictionary *dict = NULL;
            yon_dictionary_add_or_create_if_exists_with_data(dict,"window",window);
            yon_dictionary_add_or_create_if_exists_with_data(dict,"dialog",dialog);

        yon_file_chooser_set_root(dialog,target);
        if (yon_file_chooser_start(dialog)==GTK_RESPONSE_ACCEPT){
            on_move_add_accept(self,dict);
        }
    }
}

void on_move_accept(GtkWidget *self, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    repo_add_window *window = yon_dictionary_get_data(dict->first->next,repo_add_window*);


    const char *storage = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceStorageEntry));
    const char *source_repo = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceRepoEntry));
    const char *target_repo = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveTargetRepoEntry));
    const char *arch = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->MoveSourceArchEntry));
    if (yon_char_is_empty(storage)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),NOTHING_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->MoveSourceStorageEntry);
        return;
    }
    if (yon_char_is_empty(source_repo)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),NOTHING_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->MoveSourceRepoEntry);
        return;
    }
    if (yon_char_is_empty(target_repo)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),NOTHING_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->MoveTargetRepoEntry);
        return;
    }
    if (yon_char_is_empty(arch)) {
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),NOTHING_CHOSEN_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->MoveSourceArchEntry);
        return;
    }
    const char *repo_sign = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->RepoSignCombo));
    if (!yon_char_is_empty(storage)&&!yon_char_is_empty(source_repo)&&!yon_char_is_empty(target_repo)&&!yon_char_is_empty(arch)){

    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(window->PackagesList);
    int size;
    config_str parsed = NULL;
    for_iter(model,&iter){
        char *path;
        gtk_tree_model_get(model,&iter,2,&path,-1);
        yon_char_parsed_add_or_create_if_exists(parsed, &size,path+(yon_char_find_last(path,'/')>-1?yon_char_find_last(path,'/')+1:0));
    }

    if (!size) {
        yon_ubl_status_box_render(NOTHING_CHOSEN_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->PackagesTree);
        return;
    }
    char *packages = yon_char_parsed_to_string(parsed,size," ");
    char *command = NULL;
    command = yon_move_packages_command(storage,arch,source_repo,target_repo,packages,repo_sign);
    if (system(yon_debug_output("%s\n",command))){
        yon_ubl_status_box_render(PACKAGES_MOVE_ERROR_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
    } else {
        yon_ubl_status_box_render(PACKAGES_MOVE_SUCCESS_LABEL,BACKGROUND_IMAGE_SUCCESS_TYPE);
    }
    free(command);
    }
    yon_interface_update(widgets);
    gtk_widget_destroy(window->MainWindow);
    free(window);
}

void on_move_remove_package(GtkWidget *self, repo_add_window *window){
    GtkTreeIter iter;
    GtkTreeModel *model;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(window->PackagesTree)),&model,&iter)){
        gtk_list_store_remove(window->PackagesList,&iter);
    }
    if (!gtk_tree_model_get_iter_first(GTK_TREE_MODEL(window->PackagesList),&iter)){

        gtk_widget_set_sensitive(window->MoveSourceStorageEntry,1);
        gtk_widget_set_sensitive(window->MoveSourceRepoEntry,1);
        gtk_widget_set_sensitive(window->MoveSourceArchEntry,1);

        gtk_widget_set_sensitive(window->MoveTargetRepoEntry,1);
        if (window->StorageCombo&&window->RepositoryCombo&&window->ArchitectureCombo){
            gtk_widget_set_sensitive(window->StorageCombo,1);
            gtk_widget_set_sensitive(window->RepositoryCombo,1);
            gtk_widget_set_sensitive(window->ArchitectureCombo,1);
        }
    }
}


void yon_move_window_set_selected(main_window *widgets, repo_add_window *window){
    GtkTreeIter iter, itar, itor;

    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->ReposTree)),NULL,&iter)){
        int depth = gtk_tree_store_iter_depth(widgets->RepoList,&iter);
        char *storage=NULL, *repo=NULL, *arch=NULL;
            storage_struct *storage_str;
            gtk_tree_model_get(GTK_TREE_MODEL(widgets->RepoList),&iter,7,&storage_str,-1);
            if (depth==2){
                storage = ((arch_struct*)storage_str)->storage_path;
                repo = ((arch_struct*)storage_str)->repo_name;
                arch = ((arch_struct*)storage_str)->name;
            } else if (depth==1){
                storage = ((repo_struct*)storage_str)->storage_path;
                repo = ((arch_struct*)storage_str)->name;
            } else if (depth == 0){
                storage = storage_str->path;
            }
            if (!yon_char_is_empty(storage)) gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->MoveSourceStorageEntry),storage);
            while(gtk_events_pending()) gtk_main_iteration();
            if (!yon_char_is_empty(repo)) gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->MoveSourceRepoEntry),repo);
            while(gtk_events_pending()) gtk_main_iteration();
            if (!yon_char_is_empty(arch)) gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->MoveSourceArchEntry),arch);
    }
}

repo_add_window *on_move_clicked(GtkWidget *self, main_window *widgets){
    repo_add_window *window = yon_repo_add_window_new();
    yon_gtk_window_setup(GTK_WINDOW(window->MainWindow),GTK_WINDOW(widgets->Window),MOVE_PACKAGES_TITLE_LABEL,icon_path,"move-repo-window");
        gtk_label_set_text(GTK_LABEL(window->HeadLabel),MOVE_PACKAGES_TITLE_LABEL);
    gtk_button_set_label(GTK_BUTTON(window->AddButton),MOVE_LABEL);
    gtk_label_set_text(GTK_LABEL(window->PackagesToAddLabel),MOVE_PACKAGES_LABEL);
    gtk_widget_show(window->MoveSourceFrame);
    gtk_widget_show(window->MoveTargetFrame);
    gtk_widget_hide(gtk_widget_get_parent(window->PackageSignCombo));

    int size;
    config_str storages = (config_str)g_hash_table_get_keys_as_array(main_config.storages,&size);
    for (int i=0;i<size;i++){
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->MoveSourceStorageEntry),storages[i],storages[i]);
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->MoveTargetStorageEntry),storages[i],storages[i]);
    }

    GtkTreeIter iter;
    yon_sign_list_update();
    yon_combo_box_text_set_signs(GTK_COMBO_BOX_TEXT(window->RepoSignCombo));
    yon_combo_box_text_set_signs(GTK_COMBO_BOX_TEXT(window->PackageSignCombo));
    gtk_combo_box_set_active(GTK_COMBO_BOX(window->RepoSignCombo),0);
    gtk_combo_box_set_active(GTK_COMBO_BOX(window->PackageSignCombo),0);

    gtk_widget_destroy(gtk_widget_get_parent(window->StorageCombo));
    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->MoveSourceStorageEntry),"changed",G_CALLBACK(on_move_storage_changed),window);
    g_signal_connect(G_OBJECT(window->MoveSourceRepoEntry),"changed",G_CALLBACK(on_move_repo_changed),window);
    g_signal_connect(G_OBJECT(window->MoveSourceArchEntry),"changed",G_CALLBACK(on_move_arch_changed),window);

    g_signal_connect(G_OBJECT(window->MoveTargetRepoEntry),"changed",G_CALLBACK(on_move_repo_changed),window);
    g_signal_connect(G_OBJECT(window->MoveTargetArchEntry),"changed",G_CALLBACK(on_move_arch_changed),window);
    
    g_signal_connect(G_OBJECT(window->MoveSourceStorageEntry),"changed",G_CALLBACK(on_move_check_fill),window);
    g_signal_connect(G_OBJECT(window->MoveSourceRepoEntry),"changed",G_CALLBACK(on_move_check_fill),window);
    g_signal_connect(G_OBJECT(window->MoveSourceArchEntry),"changed",G_CALLBACK(on_move_check_fill),window);
    g_signal_connect(G_OBJECT(window->MoveTargetRepoEntry),"changed",G_CALLBACK(on_move_check_fill),window);
    g_signal_connect(G_OBJECT(window->MoveTargetArchEntry),"changed",G_CALLBACK(on_move_check_fill),window);

    g_signal_connect(G_OBJECT(window->AddPackageButton),"clicked",G_CALLBACK(on_move_add_package),window);
    g_signal_connect(G_OBJECT(window->RemoveButton),"clicked",G_CALLBACK(on_move_remove_package),window);

    yon_rmb_menu_setup(window->PackagesTree,(int(*)(void*))gtk_widget_is_sensitive,window->AddPackageButton,
    ADD_PACKAGE_LABEL,add_icon_name,G_CALLBACK(on_move_add_package),window,
    REMOVE_PACKAGE_LABEL,remove_icon,G_CALLBACK(on_move_remove_package),window,
    NULL);


    g_signal_connect(G_OBJECT(window->AddButton),"clicked",G_CALLBACK(on_move_accept),dict);
    // g_signal_connect(G_OBJECT(window->MoveSourceRepoEntry),"changed",G_CALLBACK(on_repo_sign_load),window);
    yon_move_window_set_selected(widgets,window);
    yon_add_window_add_chosen_packages(widgets,window);
    gtk_widget_show(window->MainWindow);
    return window;
}