#include "ubl-settings-update.h"


void on_web_publish_accept(GtkWidget *, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    web_publication_add_window *window = yon_dictionary_get_data(dict->first->next,web_publication_add_window*);

    int enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->EnablePublishCheck));
    int port_enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->PortCheck));
    char *port = yon_char_from_long(gtk_spin_button_get_value(GTK_SPIN_BUTTON(window->PortEntry)));
    int enable_browser = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->EnableWebFileBrowserCheck));

    int username_check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->UsernameCheck));
    char *username = (char*)gtk_entry_get_text(GTK_ENTRY(window->UsernameEntry));
    char *user_password = yon_char_new((char*)gtk_entry_get_text(GTK_ENTRY(window->UserPasswordEntry)));
    char *encryption = user_password[6]=='|'?yon_char_divide(user_password,6):NULL;

    if (username_check&&yon_char_is_empty(username)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->UsernameEntry);
        return;
    }
        if (strpbrk(username,"!@#%^&*\'")){
            yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),ENTRY_RESTRICTED_SYMBOL_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
            yon_ubl_status_highlight_incorrect(window->UsernameEntry);
            return;
        }
        if (username_check&&strpbrk(user_password,"!@#%^&*\'")){
            yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),PASSWORD_RESTRICTED_SYMBOL_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
            yon_ubl_status_highlight_incorrect(window->UserPasswordEntry);
            return;
        }
        // if (username_check&&encryption&&!yon_char_is_empty(encryption)&&(strlen(user_password)!=128&&strlen(user_password)!=64)){

        //     yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),PASSWORD_RESTRICTED_SYMBOL_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        //     yon_ubl_status_highlight_incorrect(window->UserPasswordEntry);
        //     return;
        // }

    char *name = (char*)gtk_entry_get_text(GTK_ENTRY(window->PathEntry));
    char *full_name = "";
    GtkTreeIter iter;
    int disabled=0;
    int overall=0;
    for_iter (GTK_TREE_MODEL(window->list),&iter){
        overall++;
        int chosen;
        char *repos;
        gtk_tree_model_get(GTK_TREE_MODEL(window->list),&iter,0,&chosen,1,&repos,-1);
        if (chosen){
            char *temp = yon_char_unite(full_name,yon_char_is_empty(full_name)?"":",",repos,NULL);
            if (!yon_char_is_empty(full_name)) free(full_name);
            full_name = temp;
        } else {
            disabled++;
        }
    }
    if (overall==disabled) {
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),NO_SHARED_REPOS_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->PathEntry);
        return;
    }
    char *final_name = yon_char_is_empty(full_name)||!disabled ? name : yon_char_unite(name,":",full_name,NULL);
    char *final = yon_char_unite(enabled?"enable":"disable",":",
    enable_browser?"listing":"",":",
    port_enabled?port:"",":",
    username_check?username:"",":",
    username_check?yon_char_is_empty(encryption)?user_password:encryption:"",":",
    username_check?!yon_char_is_empty(user_password)&&!yon_char_is_empty(encryption)?user_password:"":"",
    NULL);
    if (!yon_char_is_empty(window->name)&&strcmp(final_name,window->name)){
        yon_config_remove_by_key(window->name);
    }
    yon_config_register(REPOPUBLIC_WEB_full(final_name),REPOPUBLIC_WEB_command(final_name),final);
    yon_interface_update(widgets);
    gtk_widget_destroy(window->Window);
}

web_publication_add_window *yon_web_publication_add_window_new(){
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_web_publish_add_path);
    web_publication_add_window *window = malloc(sizeof(web_publication_add_window));
    window->Window = yon_gtk_builder_get_widget(builder,"MainWindow");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->EnablePublishCheck = yon_gtk_builder_get_widget(builder,"EnablePublishCheck");
    window->PathEntry = yon_gtk_builder_get_widget(builder,"PathEntry");
    window->PathButton = yon_gtk_builder_get_widget(builder,"PathButton");
    window->RepositoriesTree = yon_gtk_builder_get_widget(builder,"RepositoriesTree");
    window->PortCheck = yon_gtk_builder_get_widget(builder,"PortCheck");
    window->PortEntry = yon_gtk_builder_get_widget(builder,"PortEntry");
    window->EnableWebFileBrowserCheck = yon_gtk_builder_get_widget(builder,"EnableWebFileBrowserCheck");
    window->UsernameCheck = yon_gtk_builder_get_widget(builder,"UsernameCheck");
    window->UsernameEntry = yon_gtk_builder_get_widget(builder,"UsernameEntry");
    window->UserPasswordCheck = yon_gtk_builder_get_widget(builder,"UserPasswordCheck");
    window->UserPasswordCombo = yon_gtk_builder_get_widget(builder,"UserPasswordCombo");
    window->UserPasswordEntry = yon_gtk_builder_get_widget(builder,"UserPasswordEntry");
    window->AcceptButton = yon_gtk_builder_get_widget(builder,"AcceptButton");
    window->CancelButton = yon_gtk_builder_get_widget(builder,"CancelButton");
    window->HeadLabel = yon_gtk_builder_get_widget(builder,"HeadLabel");
    window->PasswordButton = yon_gtk_builder_get_widget(builder,"PasswordButton");
    window->list = GTK_LIST_STORE(gtk_builder_get_object(builder,"liststore1"));
    window->SelectionCellRenderer = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"SelectionCellRenderer"));

    yon_gtk_entry_set_password_visibility_icon(GTK_ENTRY(window->UserPasswordEntry));
    window->name=NULL;
    g_signal_connect(G_OBJECT(window->SelectionCellRenderer),"toggled",G_CALLBACK(on_cell_renderer_toggle_toggled),window->RepositoriesTree);
    g_signal_connect(G_OBJECT(window->PathButton),"clicked",G_CALLBACK(on_file_chooser_open),window->PathEntry);
    g_signal_connect(G_OBJECT(window->PathEntry),"changed",G_CALLBACK(on_web_publish_path_changed),window);
    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
    g_signal_connect(G_OBJECT(window->PasswordButton),"clicked",G_CALLBACK(on_password_open),window);
    g_signal_connect(G_OBJECT(window->UsernameCheck),"toggled",G_CALLBACK(on_web_user_check),window);
    g_signal_connect(G_OBJECT(window->PortCheck),"toggled",G_CALLBACK(yon_gtk_widget_set_sensitive_from_toggle_button),window->PortEntry);
    g_signal_connect(G_OBJECT(window->UserPasswordCombo),"changed",G_CALLBACK(yon_gtk_widget_set_sensitive_from_combo_box_inversed),window->PasswordButton);
    g_signal_connect(G_OBJECT(window->UserPasswordCombo),"changed",G_CALLBACK(yon_gtk_widget_set_sensitive_from_combo_box_inversed),window->UserPasswordEntry);
    g_signal_connect(G_OBJECT(window->PortEntry),"insert-text",G_CALLBACK(yon_on_text_insert_only_digits),NULL);
    gtk_widget_show(window->Window);
    
    return window;
}


void on_web_user_check(GtkToggleButton *self, web_publication_add_window *window){
    int status = gtk_toggle_button_get_active(self);
    int status2 = gtk_combo_box_get_active(GTK_COMBO_BOX(window->UserPasswordCombo));
    gtk_widget_set_sensitive(window->UsernameEntry,status);
    gtk_widget_set_sensitive(window->UserPasswordCombo,status);
    gtk_widget_set_sensitive(window->PasswordButton,status&&status2);
    gtk_widget_set_sensitive(window->UserPasswordEntry,(status&&status2));
}

void on_web_publish_path_changed(GtkWidget *, web_publication_add_window *window){
    gtk_list_store_clear(window->list);
    char *path = (char*)gtk_entry_get_text(GTK_ENTRY(window->PathEntry));
    if (!yon_file_is_directory(path)){
        return;
    }
    if (yon_char_is_empty(path) || access(path,F_OK)) return;
    int size;
    config_str parsed = yon_file_ls(path,&size);
    GtkTreeIter iter;
    for (int i=0;i<size;i++){
        struct stat path_stat;
        char *cur_path = yon_char_unite(path,"/",parsed[i],NULL);
        stat(cur_path, &path_stat);
        if (S_ISDIR(path_stat.st_mode)&&strcmp(parsed[i],"pool")&&strcmp(parsed[i],"..")&&strcmp(parsed[i],".")){
            gtk_list_store_append(window->list,&iter);
            gtk_list_store_set(window->list,&iter,0,1,1,parsed[i],-1);
        }
        free(cur_path);
    }
    yon_char_parsed_free(parsed,size);
}

void on_web_publish_add(GtkWidget *,main_window *widgets){
    gtk_tree_selection_unselect_all(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->MirrorTree)));
    web_publication_add_window *window = yon_web_publication_add_window_new();
    yon_gtk_window_setup(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->Window),ADD_REPO_LABEL,icon_path,"web_publish_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->AcceptButton),"clicked",G_CALLBACK(on_web_publish_accept),dict);
}

void on_web_publish_remove(GtkWidget *self,main_window *widgets){
    dialog_confirmation_data *data = yon_confirmation_dialog_data_new();
    data->action_text=REMOVE_REPO_WARNING_LABEL;
    data->function=(void(*)(void*,void*))on_web_publish_remove_accept;
    data->data = widgets;
    yon_confirmation_dialog_call(self,data);
}

void on_web_publish_remove_accept(GtkWidget *, main_window *widgets){
    GtkTreeModel *model=NULL;
    GtkTreeIter iter;
    if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->WebPublicationTree)),&model,&iter)) {
        return;
    }
    char *full_name = NULL;
    gtk_tree_model_get(model,&iter,8,&full_name,-1);
    yon_config_remove_by_key(full_name);
    yon_interface_update(widgets);
}
void on_web_publish_edit(GtkWidget *,main_window *widgets){
    web_publication_add_window *window = yon_web_publication_add_window_new();
    gtk_label_set_text(GTK_LABEL(window->HeadLabel),EDIT_WEB_LABEL);
    yon_gtk_window_setup(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->Window),ADD_WEB_LABEL,icon_path,"web_publish_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->AcceptButton),"clicked",G_CALLBACK(on_web_publish_accept),dict);
    GtkTreeIter iter;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->WebPublicationTree)),NULL,&iter)){
        char *storage;
        char *repos;
        char *full;
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->WebPublicationList),&iter,1,&storage,2,&repos,8,&full,-1);
        gtk_entry_set_text(GTK_ENTRY(window->PathEntry),storage);
        while(gtk_events_pending()) gtk_main_iteration();
        if(!yon_char_is_empty(repos)){
            int size;
            config_str parsed = yon_char_parse(repos,&size,"\n");
            if (size){
                GtkTreeIter itar;
                for_iter(GTK_TREE_MODEL(window->list),&itar){
                    char *target;
                    gtk_tree_model_get(GTK_TREE_MODEL(window->list),&itar,1,&target,-1);
                    if (yon_char_parsed_check_exist(parsed,size,target)==-1){
                        gtk_list_store_set(window->list,&itar,0,0,-1);
                    }
                }
            }
        }
        window->name = full;
        char *parameter = config(full);
        int size;
        config_str parsed = yon_char_parse(parameter,&size,":");
        if (size){
            if (!strcmp(parsed[0],"enable")||!strcmp(parsed[0],"yes")){
                gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(window->EnablePublishCheck),1);
            }
            if (size>1&&!strcmp(parsed[1],"listing")){
                gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(window->EnableWebFileBrowserCheck),1);
            }
            if (size>2&&!yon_char_is_empty(parsed[2])){
                gtk_spin_button_set_value(GTK_SPIN_BUTTON(window->PortEntry),atol(parsed[2]));
                gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(window->PortCheck),1);
            }
            if (size>3&&!yon_char_is_empty(parsed[3])){
                gtk_entry_set_text(GTK_ENTRY(window->UsernameEntry),parsed[3]);
                gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(window->UsernameCheck),1);
            }
            if (size>5&&!yon_char_is_empty(parsed[4])&&!yon_char_is_empty(parsed[5])){
                gtk_combo_box_set_active(GTK_COMBO_BOX(window->UserPasswordCombo),1);
                if (!strcmp(parsed[4],"sha256")||!strcmp(parsed[4],"sha512")){
                    gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->UserPasswordCombo),parsed[4]);
                    char *temp = yon_char_unite(parsed[4],"|",parsed[5],NULL);
                    gtk_entry_set_text(GTK_ENTRY(window->UserPasswordEntry),temp);
                    free(temp);

                } else {
                    gtk_entry_set_text(GTK_ENTRY(window->UserPasswordEntry),parsed[4]);
                    if (size>5)
                        gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->UserPasswordCombo),"");
                }
            }
        }
    }

    gtk_widget_show(window->Window);
}