#include "ubl-settings-repomanager.h"

void on_add_target_repo_selection_changed(GtkWidget *target,repo_add_window *window){
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(window->RepositoryCombo));
    char *path_str = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StorageCombo));
    if (!yon_char_is_empty(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->RepositoryCombo),repos[i],repos[i]);
        }
    }
}

void on_add_target_arch_selection_changed(GtkWidget *target,repo_add_window *window){
    gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(window->ArchitectureCombo));
    char *storage_str = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StorageCombo));
    char *repo_str = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->RepositoryCombo));
    if (!yon_char_is_empty(repo_str)&&!yon_char_is_empty(storage_str)){
        storage_struct *storage = g_hash_table_lookup(main_config.storages,storage_str);
        repo_struct *repo = g_hash_table_lookup(storage->repos,repo_str);
        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->ArchitectureCombo),archs[i],archs[i]);
        }
        gtk_widget_set_sensitive(window->RepoSignCombo,1);
    } else {
        gtk_widget_set_sensitive(window->RepoSignCombo,0);

    }
}

void on_arch_chosen(GtkWidget *target,repo_add_window *window){
    char *path_str = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->ArchitectureCombo));
    if (!yon_char_is_empty(path_str)){
        gtk_widget_set_sensitive(window->PackageSignCombo,1);
    } else {
        gtk_widget_set_sensitive(window->PackageSignCombo,0);
    }
}

void on_add_target_package_selection_changed(GtkWidget *target,repo_add_window *window){
    gtk_list_store_clear(GTK_LIST_STORE(window->PackagesList));
    if (gtk_combo_box_get_active(GTK_COMBO_BOX(window->ArchitectureCombo))==-1){
        gtk_widget_set_sensitive(window->AddPackageButton,0);
    } else {
        gtk_widget_set_sensitive(window->AddPackageButton,1);
    }
}

void on_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);
            }

        }
    }
}

void on_file_chooser_file_activate(GtkWidget *self, dictionary *dict){
    on_add_accept(self,dict);
}


void on_add_package(GtkWidget *self, repo_add_window *window){
    filechooser_window *dialog = yon_file_chooser_window_new(GTK_FILE_CHOOSER_ACTION_OPEN);
    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),CHOSE_PACKAGES_TITLE_LABEL,icon_path,"filechooserWindow");

    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);

    gtk_widget_show(dialog->ChooseFolderCheck);
    gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog->MainFileChooser),1);
    if (yon_file_chooser_start(dialog)==GTK_RESPONSE_ACCEPT){
        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);
        if (!yon_char_is_empty(main_config.last_selection)) free(main_config.last_selection);
        main_config.last_selection = yon_char_new(dialog->last_any_selection);
        on_add_accept(self,dict);
    }
    gtk_widget_destroy(dialog->Window);
    free(dialog);
}

void on_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);
    }
}

void on_add_window_tree_changed(GtkWidget *self, repo_add_window *window){
    gtk_label_set_text(GTK_LABEL(window->InfoLabel),"");
    GtkTreeModel *model;
    GtkTreeIter iter;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(window->PackagesTree)),&model,&iter)){
        gtk_widget_set_sensitive(window->RemoveButton,1);
        char *target;
        gtk_tree_model_get(model,&iter,2,&target,-1);
        int size;
        config_str info = yon_config_load(get_package_info_command(target),&size);
        yon_package_info_set_markup(info,size);
        char *result = yon_char_parsed_to_string(info,size,"");
        gtk_label_set_markup(GTK_LABEL(window->InfoLabel),result);
        yon_char_parsed_free(info,size);
        if (!yon_char_is_empty(result)) free(result);
    } else {
        gtk_widget_set_sensitive(window->RemoveButton,0);
    }
}


void on_add_packages_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->StorageCombo));
    const char *repo = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->RepositoryCombo));
    const char *arch = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->ArchitectureCombo));
    
    if (yon_char_is_empty(storage)||yon_char_is_empty(repo)||yon_char_is_empty(arch)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->StorageCombo);
        return;
    }
    if (yon_char_is_empty(repo)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->RepositoryCombo);
        return;
    }
    if (yon_char_is_empty(arch)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->ArchitectureCombo);
        return;
    }

    const char *repo_sign = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->RepoSignCombo));
    const char *package_sign = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->PackageSignCombo));
    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);
    }

    if (!size){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),PACKAGES_REMOVE_ERROR_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->PackagesTree);
        return;
    }

    char *packages = yon_char_parsed_to_string(parsed,size," ");
    char *command = NULL;
    if (repo_sign&&package_sign){
        command = add_packages_sign_command(storage,arch,repo,repo_sign,package_sign,packages);
    } else if (!yon_char_is_empty(repo_sign)){
        command = add_packages_repo_sign_command(storage,arch,repo,repo_sign,packages);
    } else if (!yon_char_is_empty(package_sign)){
        command = add_packages_package_sign_command(storage,arch,repo,package_sign,packages);
    } else {
        command = add_packages_command(storage,arch,repo,packages);
    }

    if (system(yon_debug_output("%s\n",command))){
        yon_ubl_status_box_render(PACKAGES_ADD_ERROR_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
    } else {
        yon_ubl_status_box_render(PACKAGES_ADD_SUCCESS_LABEL,BACKGROUND_IMAGE_SUCCESS_TYPE);
    }
    gtk_widget_destroy(window->MainWindow);
    yon_interface_update(widgets);
    free(window);

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

// void on_repo_sign_load(GtkWidget *self, repo_add_window *window){
//     GtkTreeIter iter;
//     yon_gtk_tree_iter_get_from_combo_box_id(GTK_COMBO_BOX(self),GTK_TREE_MODEL(window->tree_copy),&iter);
//     char *sign;
//     gtk_tree_model_get(GTK_TREE_MODEL(window->tree_copy),&iter,5,&sign,-1);
//     if (!yon_char_is_empty(sign))
//         gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->RepoSignCombo),sign);
// }


void yon_add_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->StorageCombo),storage);
            while(gtk_events_pending()) gtk_main_iteration();
            if (!yon_char_is_empty(repo)) gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->RepositoryCombo),repo);
            while(gtk_events_pending()) gtk_main_iteration();
            if (!yon_char_is_empty(arch)) gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->ArchitectureCombo),arch);
    }
}

repo_add_window *yon_repo_add_window_new(){
    repo_add_window *window = malloc(sizeof(repo_add_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_repo_add);
    window->MainWindow = yon_gtk_builder_get_widget(builder,"MainWindow");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->StorageCombo = yon_gtk_builder_get_widget(builder,"StorageCombo");
    window->HeadLabel = yon_gtk_builder_get_widget(builder,"HeadLabel");
    window->RepositoryCombo = yon_gtk_builder_get_widget(builder,"RepositoryCombo");
    window->ArchitectureCombo = yon_gtk_builder_get_widget(builder,"ArchitectureCombo");
    window->MoveSourceFrame = yon_gtk_builder_get_widget(builder,"MoveSourceFrame");
    window->MoveSourceStorageEntry = yon_gtk_builder_get_widget(builder,"MoveSourceStorageEntry");
    window->MoveSourceRepoEntry = yon_gtk_builder_get_widget(builder,"MoveSourceRepoEntry");
    window->MoveSourceArchEntry = yon_gtk_builder_get_widget(builder,"MoveSourceArchEntry");
    window->MoveTargetFrame = yon_gtk_builder_get_widget(builder,"MoveTargetFrame");
    window->MoveTargetStorageEntry = yon_gtk_builder_get_widget(builder,"MoveTargetStorageEntry");
    window->MoveTargetRepoEntry = yon_gtk_builder_get_widget(builder,"MoveTargetRepoEntry");
    window->MoveTargetArchEntry = yon_gtk_builder_get_widget(builder,"MoveTargetArchEntry");
    window->PackageSignCombo = yon_gtk_builder_get_widget(builder,"PackageSignCombo");
    window->RepoSignCombo = yon_gtk_builder_get_widget(builder,"RepoSignCombo");
    window->AddPackageButton = yon_gtk_builder_get_widget(builder,"AddPackageButton");
    window->RemoveButton = yon_gtk_builder_get_widget(builder,"RemoveButton");
    window->PackagesTree = yon_gtk_builder_get_widget(builder,"PackagesTree");
    window->InfoLabel = yon_gtk_builder_get_widget(builder,"InfoLabel");
    window->PackagesToAddLabel = yon_gtk_builder_get_widget(builder,"PackagesToAddLabel");
    window->AddButton = yon_gtk_builder_get_widget(builder,"AddButton");
    window->CancelButton = yon_gtk_builder_get_widget(builder,"CancelButton");
    window->PackagesList = GTK_LIST_STORE(gtk_builder_get_object(builder,"PackagesList"));

    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
    g_signal_connect(G_OBJECT(window->PackagesTree),"cursor-changed",G_CALLBACK(on_add_window_tree_changed),window);

    
    window->added_packages_archs = NULL;
    window->removed_packages_archs = NULL;

    return window;
}

void yon_add_window_add_chosen_packages(main_window *widgets, repo_add_window *window){
    GtkTreeIter iter;
    GtkTreeModel *model = GTK_TREE_MODEL(widgets->RepoFileList);
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->RepoFileTree)),NULL,&iter)){
        char *target, *path;
        gtk_tree_model_get(model,&iter,1,&target,2,&path,-1);
        gtk_list_store_append(window->PackagesList,&iter);
        gtk_list_store_set(window->PackagesList,&iter,1,target,2,path,-1);
    }
    GList *list = gtk_tree_selection_get_selected_rows(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->RepoPackagesTree)),NULL);
    GList *liter;
    if (list){
        for (liter=list;liter;liter=liter->next){
            gtk_tree_model_get_iter(model,&iter,(GtkTreePath*)liter->data);
            char *target, *path;
            gtk_tree_model_get(model,&iter,2,&target,-1);
            gtk_list_store_append(window->PackagesList,&iter);
            gtk_list_store_set(window->PackagesList,&iter,1,target,-1);
        }
    }
}

void on_add_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),ADD_PACKAGES_TITLE_LABEL,icon_path,"add-repo-window");
    gtk_label_set_text(GTK_LABEL(window->HeadLabel),ADD_PACKAGES_TITLE_LABEL);
    GtkTreeIter iter;
    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->StorageCombo),storages[i],storages[i]);
    }

    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);

    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->StorageCombo),"changed",G_CALLBACK(on_add_target_repo_selection_changed),window);
    g_signal_connect(G_OBJECT(window->RepositoryCombo),"changed",G_CALLBACK(on_add_target_arch_selection_changed),window);
    g_signal_connect(G_OBJECT(window->ArchitectureCombo),"changed",G_CALLBACK(on_arch_chosen),window);
    g_signal_connect(G_OBJECT(window->ArchitectureCombo),"changed",G_CALLBACK(on_add_target_package_selection_changed),window);
    g_signal_connect(G_OBJECT(window->AddButton),"clicked",G_CALLBACK(on_add_packages_accept),dict);
    g_signal_connect(G_OBJECT(window->AddPackageButton),"clicked",G_CALLBACK(on_add_package),window);
    g_signal_connect(G_OBJECT(window->RemoveButton),"clicked",G_CALLBACK(on_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_add_package),window,
    REMOVE_PACKAGE_LABEL,remove_icon,G_CALLBACK(on_remove_package),window,
    NULL);

    // g_signal_connect(G_OBJECT(window->RepositoryCombo),"changed",G_CALLBACK(on_repo_sign_load),window);
    yon_add_window_set_selected(widgets,window);
    // yon_add_window_add_chosen_packages(widgets,window);
    gtk_widget_show(window->MainWindow);
}