#include "ubl-settings-events.h"

add_window *yon_add_window_new(){
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_add);
    add_window *window = malloc(sizeof(add_window));

    window->MainWindow=yon_gtk_builder_get_widget(builder,"MainWindow");
    window->StatusBox=yon_gtk_builder_get_widget(builder,"StatusBox");
    window->CancelButton=yon_gtk_builder_get_widget(builder,"CancelButton");
    window->SaveButton=yon_gtk_builder_get_widget(builder,"SaveButton");
    window->AutosetButton=yon_gtk_builder_get_widget(builder,"AutosetButton");
    window->IDEntry=yon_gtk_builder_get_widget(builder,"IDEntry");
    window->RuleEntry=yon_gtk_builder_get_widget(builder,"RuleEntry");
    window->DescriptionTextView=yon_gtk_builder_get_widget(builder,"DescriptionTextView");

    g_signal_connect(G_OBJECT(window->AutosetButton),"clicked",G_CALLBACK(on_autoset_clicked),window);
    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
    g_signal_connect(G_OBJECT(window->IDEntry),"changed",G_CALLBACK(on_id_check),NULL);
    g_signal_connect(G_OBJECT(window->IDEntry),"changed",G_CALLBACK(on_id_check),NULL);

    return window;
}

void on_id_check(GtkEntry *self){
    const char *text = gtk_entry_get_text(self);
    if (yon_char_is_empty(text)){
        gtk_entry_set_icon_from_icon_name(self,GTK_ENTRY_ICON_SECONDARY,"");
        return;
    }
    if (g_hash_table_lookup(main_config.trees,text)){
        gtk_entry_set_icon_from_icon_name(self,GTK_ENTRY_ICON_SECONDARY,id_exist_icon_path);
    } else {
        gtk_entry_set_icon_from_icon_name(self,GTK_ENTRY_ICON_SECONDARY,id_free_icon_path);

    }

}

char *yon_id_from_int(int id){
    char *final=NULL;
    char *id_str = yon_char_from_int(id);
    char *cur = malloc(sizeof(char)*9);
    int id_size = strlen(id_str);
    memset(cur,0,9);
    memset(cur,48,8);
    memcpy(cur+(8-id_size),id_str,id_size);
    (final) = cur; 
    free(id_str);
    return final;
}

void on_autoset_clicked(GtkWidget *,add_window *window){
    char *id = yon_char_from_int(main_config.comments_size);
    int rand_id = rand()%100000000;
    char *comment = yon_id_from_int(rand_id);
        
        for (;g_hash_table_lookup(main_config.trees,comment);rand_id++){
            if (!yon_char_is_empty(comment)) free(comment);
            comment = yon_id_from_int(rand_id);
        }
        gtk_entry_set_text(GTK_ENTRY(window->IDEntry),comment);
    free(id);
    free(comment);
}

void on_description_changed(GtkTextBuffer *self, add_window *window){
    GtkTextIter iterstart, iterend; 
    GtkTextBuffer *buffer = self;
    gtk_text_buffer_get_start_iter(buffer,&iterstart);
    gtk_text_buffer_get_end_iter(buffer,&iterend);
    if (!yon_char_is_empty(window->last_description)) free(window->last_description);
    window->last_description = yon_char_new(gtk_text_buffer_get_text(buffer,&iterstart,&iterend,0));
}

void on_insert_clicked(GtkWidget *,main_window *widgets){
    add_window *window = yon_add_window_new();

    yon_gtk_window_setup(GTK_WINDOW(window->MainWindow),GTK_WINDOW(widgets->Window),ADD_TOOLTIP_LABEL,icon_path,"add_window");

    GtkListBoxRow *row = gtk_list_box_get_selected_row(GTK_LIST_BOX(widgets->TabsBox));
    while(gtk_events_pending()) gtk_main_iteration();
    yon_menu_table *table = g_object_get_data(G_OBJECT(row),"menu_table");
    on_autoset_clicked(NULL,window);
    if (!yon_char_is_empty(table->rule))
        gtk_entry_set_text(GTK_ENTRY(window->RuleEntry),table->rule);
    if (!yon_char_is_empty(table->description)){
        gtk_text_buffer_set_text(gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->DescriptionTextView)),_(table->description),strlen(_(table->description)));
        window->last_description = yon_char_new(table->description);
    }
    g_signal_connect(G_OBJECT(gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->DescriptionTextView))),"changed",G_CALLBACK(on_description_changed),window);

    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->SaveButton),"clicked",G_CALLBACK(on_insert_accept),dict);
    gtk_widget_show(window->MainWindow);
}

void on_add_clicked(GtkWidget *,main_window *widgets){
    add_window *window = yon_add_window_new();

    yon_gtk_window_setup(GTK_WINDOW(window->MainWindow),GTK_WINDOW(widgets->Window),ADD_TOOLTIP_LABEL,icon_path,"add_window");

    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->SaveButton),"clicked",G_CALLBACK(on_add_accept),dict);
    gtk_widget_show(window->MainWindow);
}

void on_add_accept(GtkWidget *, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    add_window *window = yon_dictionary_get_data(dict->first->next,add_window*);
    GtkTextIter iterstart, iterend; 
    GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->DescriptionTextView));
    gtk_text_buffer_get_start_iter(buffer,&iterstart);
    gtk_text_buffer_get_end_iter(buffer,&iterend);

    char *id = (char*)gtk_entry_get_text(GTK_ENTRY(window->IDEntry));
    char *rule = (char*)gtk_entry_get_text(GTK_ENTRY(window->RuleEntry));
    char *description = gtk_text_buffer_get_text(buffer,&iterstart,&iterend,0);

    if(yon_char_is_empty(id)&&yon_char_is_empty(rule)&&yon_char_is_empty(description)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->IDEntry);
        return;
    }

    if (g_hash_table_lookup(main_config.trees,id)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),ALREADY_EXISTS_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->IDEntry);
        return;
    }

    // char *full_value = yon_char_unite(!yon_char_is_empty(rule)?rule:"","#",description,NULL);
    if (yon_char_is_empty(id)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->IDEntry);
        return;
    } 
    GtkListBoxRow *selected_row = gtk_list_box_get_selected_row(GTK_LIST_BOX(widgets->TabsBox));
    yon_menu_table *position = NULL;
    if (selected_row)
    position = yon_menu_table_get_selected(selected_row);

    yon_menu_table_row_insert(GTK_LIST_BOX(widgets->TabsBox),id,rule,description,position,widgets);
    gtk_widget_destroy(window->MainWindow);
    // g_thread_new("update_thread",(GThreadFunc)yon_interface_update,widgets);
}

void yon_menu_table_insert(yon_menu_table *table,yon_menu_table *position){
    if (position){
        g_hash_table_insert(main_config.trees,yon_char_new(table->key),table);
        g_sequence_insert_before(g_sequence_iter_next(position->order_position),table);

    } else {
        g_hash_table_insert(main_config.trees,yon_char_new(table->key),table);
        g_sequence_append(main_config.trees_order,table);
    }
}

void on_insert_accept(GtkWidget *, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    add_window *window = yon_dictionary_get_data(dict->first->next,add_window*);
    GtkTextIter iterstart, iterend; 
    GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->DescriptionTextView));
    gtk_text_buffer_get_start_iter(buffer,&iterstart);
    gtk_text_buffer_get_end_iter(buffer,&iterend);

    char *id = (char*)gtk_entry_get_text(GTK_ENTRY(window->IDEntry));
    char *rule = (char*)gtk_entry_get_text(GTK_ENTRY(window->RuleEntry));
    char *description = window->last_description;

    if(yon_char_is_empty(id)&&yon_char_is_empty(rule)&&yon_char_is_empty(description)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->IDEntry);
        return;
    }

    if (g_hash_table_lookup(main_config.trees,id)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),ALREADY_EXISTS_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->IDEntry);
        return;
    }

    if (yon_char_is_empty(id)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->IDEntry);
        return;
    } 
    
    GtkListBoxRow *selected_row = gtk_list_box_get_selected_row(GTK_LIST_BOX(widgets->TabsBox));
    yon_menu_table *position = yon_menu_table_get_selected(selected_row);

    yon_menu_table_row_insert(GTK_LIST_BOX(widgets->TabsBox),id,rule,description,position,widgets);
    gtk_widget_destroy(window->MainWindow);
}

void on_remove_clicked(GtkWidget *,main_window *widgets){

    GtkListBoxRow *row = gtk_list_box_get_selected_row(GTK_LIST_BOX(widgets->TabsBox));
    yon_menu_table *table = g_object_get_data(G_OBJECT(row),"menu_table");
    dialog_confirmation_data *data = yon_confirmation_dialog_data_new();
    data->title=TITLE_LABEL;
    data->action_text=!yon_char_is_empty(table->rule)?REMOVE_LABEL(table->key):REMOVE_COMMENT_LABEL;
    if (yon_confirmation_dialog_call(widgets->Window,data)!=GTK_RESPONSE_ACCEPT){
        return;
    }
    yon_menu_table_destroy(table);
    gtk_widget_destroy(GTK_WIDGET(row));
}

yon_menu_table *yon_menu_table_row_insert(GtkListBox *List, char *key, char *rule,
                                            char *description,yon_menu_table *position,main_window *widgets){
    yon_menu_table *table = yon_menu_table_new();    

    if (!yon_char_is_empty(key)){
        table->key = yon_char_new(key);
    }

    if (!yon_char_is_empty(rule)){
        table->rule = yon_char_new(rule);
    }
    if (!yon_char_is_empty(description)){
        table->description = yon_char_new(description);
    }
    int config_size;
    config_str config = yon_config_get_all_keys(&config_size);
    if (!config_size){
        table->enabled = 1;
    } else {
        yon_char_parsed_free(config,config_size);
    }
    yon_menu_table_update(table);
    table->order_position = g_sequence_append(main_config.trees_order,table);
    yon_menu_table_insert(table,position);
    
    GtkWidget *row = gtk_list_box_row_new();
    gtk_widget_show(row);
    gtk_container_add(GTK_CONTAINER(row),table->MainBox);
    g_object_set_data(G_OBJECT(row),"menu_table",table);
    GtkListBoxRow *selected_row = NULL;
    if (position){
        selected_row = gtk_list_box_get_selected_row(GTK_LIST_BOX(widgets->TabsBox));
    }
    gtk_list_box_insert(GTK_LIST_BOX(List),GTK_WIDGET(row),selected_row?gtk_list_box_row_get_index(selected_row)+1:-1);
    gtk_list_box_select_row(GTK_LIST_BOX(List),GTK_LIST_BOX_ROW(row));
    yon_list_resize(widgets);
    return table;
}