#include "ubl-settings-repomanager.h"


void on_repo_signed(GtkWidget *self, storage_repo_block *block){
    storage_config_window *window = g_object_get_data(G_OBJECT(self),"window");
    const char *sign = gtk_combo_box_get_active_id(GTK_COMBO_BOX(block->SignatureCombo));
    const char *storage_id = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
    storage_struct *storage = g_hash_table_lookup(window->storages_copy,storage_id);
    repo_struct *repo = g_hash_table_lookup(storage->repos,block->repo_name);
    // yon_repo_struct_sign(storage,repo,sign);
    yon_config_register(repo->path,STORAGE_command,(char*)sign);
    if (!yon_char_is_empty(block->sign_request)) free(block->sign_request);
    block->sign_request = yon_char_new(sign);
}

void on_repo_removed(GtkWidget *self,storage_repo_block *block){
    storage_config_window *window = g_object_get_data(G_OBJECT(self),"window");
    const char *storage_id = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->StoragePathCombo));
    storage_struct *storage = g_hash_table_lookup(window->storages_copy,storage_id);
    if (g_hash_table_lookup(storage->repos,block->repo_name)){
        repo_struct *repo = g_hash_table_lookup(storage->repos,block->repo_name);
        // yon_storage_struct_remove(storage,repo);
    yon_config_remove_element(storage->path,repo->path,",");
        g_hash_table_remove(storage->repos,block->repo_name);
        gtk_widget_destroy(block->MainBox);
        yon_storage_repo_block_destroy(block);
    }
    
}

storage_repo_block *yon_storage_repo_block_new(){
    storage_repo_block *block = malloc(sizeof(storage_repo_block));
    
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_repo_block);
    block->MainBox = yon_gtk_builder_get_widget(builder,"MainBox");
    block->SignatureCombo = yon_gtk_builder_get_widget(builder,"SignatureCombo");
    block->RepoNameEntry = yon_gtk_builder_get_widget(builder,"RepoNameEntry");
    block->RepoRemoveButton = yon_gtk_builder_get_widget(builder,"RepoRemoveButton");

    block->repo_name=NULL;
    block->storage_path=NULL;
    block->sign_request=NULL;

    g_object_set_data(G_OBJECT(block->MainBox),"repo_block",block);
    g_object_set_data(G_OBJECT(block->SignatureCombo),"repo_block",block);
    g_object_set_data(G_OBJECT(block->RepoRemoveButton),"repo_block",block);


    yon_combo_box_text_set_signs(GTK_COMBO_BOX_TEXT(block->SignatureCombo));
    gtk_combo_box_set_active(GTK_COMBO_BOX(block->SignatureCombo),0);

    g_signal_connect(block->SignatureCombo,"changed",G_CALLBACK(on_repo_signed),block);
    g_signal_connect(block->RepoRemoveButton,"clicked",G_CALLBACK(on_repo_removed),block);
    return block;
}

void yon_storage_repo_block_destroy(storage_repo_block *block){
    if (!yon_char_is_empty(block->repo_name)) free(block->repo_name);
    if (!yon_char_is_empty(block->storage_path)) free(block->storage_path);
    free(block);
}