#include "ubl-settings-repomanager.h"
#include "pwquality.h"

void on_calendar_open(GtkWidget *self,key_creation_window *window){
    yon_calendar_popover_open(GTK_ENTRY(window->ExpireEntry),self);
}

void on_key_generate_accept(GtkWidget *self, key_creation_window* window){
    const char *name = gtk_entry_get_text(GTK_ENTRY(window->NameEntry));
    const char *type = gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->EncryptionCombo));
    const char *email = gtk_entry_get_text(GTK_ENTRY(window->EmailEntry));
    char *strength = yon_char_from_long(gtk_spin_button_get_value(GTK_SPIN_BUTTON(window->KeyStrengthSpin)));
    const char *comment = gtk_entry_get_text(GTK_ENTRY(window->CommentsEntry));
    if (!yon_char_is_empty(name)&&strlen(name)<5){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),NAME_SHORT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->NameEntry);
        return;
    }
    if (!yon_char_is_empty(email)&&!g_regex_match_simple("^(?!.*[@.]{2})(?!^[@.])[^@.]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$",email,0,0)){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),yon_char_get_localised_from_lib(EMAIL_INVALID_LABEL),5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(window->EmailEntry);
        return;
    }
    GtkWidget *highlight_target=NULL;
    if (yon_char_is_empty(name)){
        highlight_target=window->NameEntry;
    } else if (yon_char_is_empty(type)){
        highlight_target=window->EncryptionCombo;
    } else if (yon_char_is_empty(email)){
        highlight_target=window->EmailEntry;
    } else if (yon_char_is_empty(strength)){
        highlight_target=window->KeyStrengthSpin;
    }
    if (highlight_target){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(highlight_target);
        return;
    }
    if (highlight_target){
        yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
        yon_ubl_status_highlight_incorrect(highlight_target);
        return;
    }
    char *expire = NULL;
    if (gtk_combo_box_get_active(GTK_COMBO_BOX(window->ExpireCombo))==1){
        GDateTime *datetime = g_date_time_new_from_unix_local(yon_calendar_get_last_date());
        expire = g_date_time_format(datetime,"%Y%m%dT000000");
        g_date_time_unref(datetime);

    }
    const char *password = gtk_entry_get_text(GTK_ENTRY(window->PasswordEntry));
    // const char *password_confirm = gtk_entry_get_text(GTK_ENTRY(window->PasswordConfirmationEntry));
    int ex_status=0;
    if (yon_char_is_empty(password)){

        char *command = yon_generate_key_no_password_command(type,name,email,strength,comment,expire,password);
        yon_debug_output("%s\n",command);
        yon_terminal_window_launch_shell(GTK_WINDOW(window->Window),(yon_debug_output("%s\n",command)),yon_char_get_localised_from_lib(SUCCESS_LABEL),yon_char_get_localised_from_lib(FAIL_LABEL));
    } else {
        for (int i=0;i<strlen(password);i++){
            if (!g_ascii_isgraph(password[i])){
                yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),PASSWORD_INVALID_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
                yon_ubl_status_highlight_incorrect(window->PasswordEntry);
                return;
            }
        }
        char *command = yon_generate_key_command(type,name,email,strength,comment,expire,password);
        yon_debug_output("%s\n",command);
        yon_terminal_window_launch_shell(GTK_WINDOW(window->Window),yon_debug_output("%s\n",command),yon_char_get_localised_from_lib(SUCCESS_LABEL),yon_char_get_localised_from_lib(FAIL_LABEL));
    }
    gtk_widget_destroy(window->Window);
    yon_sign_list_update();
}

gboolean yon_pwquality_check(const char *password){
    pwquality_settings_t *settings = pwquality_default_settings();
    double strength = (double)pwquality_check(settings,password,NULL,NULL,NULL);
    return strength;
}

char *yon_pwquality_error_check(const char *password){
    void *auxerror = NULL;
    pwquality_settings_t *settings = pwquality_default_settings();
    int password_strength = pwquality_check(settings,password,NULL,NULL,&auxerror);
    const char *add_info = NULL;
    if (auxerror){
        add_info = pwquality_strerror(NULL,4094,password_strength,auxerror);
    }
    if (password_strength<30){
        return yon_char_new(add_info);
    }
}

void on_key_password_clicked(GtkWidget *, key_creation_window *window){
    yon_password_window *dialog = yon_password_open(GTK_ENTRY(window->PasswordEntry));

    yon_password_hash_list_set(dialog,NULL,NULL,0);
    yon_password_function_set(dialog,(double(*)(const char*))yon_pwquality_check,(char*(*)(const char*))yon_pwquality_error_check);
}

key_creation_window *yon_key_creation_window_new(){
    key_creation_window *window = malloc(sizeof(key_creation_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_key);
    window->Window = yon_gtk_builder_get_widget(builder,"MainWindow");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->HeadLabel = yon_gtk_builder_get_widget(builder,"HeadLabel");
    window->NameEntry = yon_gtk_builder_get_widget(builder,"NameEntry");
    window->EmailEntry = yon_gtk_builder_get_widget(builder,"EmailEntry");
    window->CommentsEntry = yon_gtk_builder_get_widget(builder,"CommentsEntry");
    window->EncryptionCombo = yon_gtk_builder_get_widget(builder,"EncryptionCombo");
    window->KeyStrengthSpin = yon_gtk_builder_get_widget(builder,"KeyStrengthSpin");
    window->ExpireCombo = yon_gtk_builder_get_widget(builder,"ExpireCombo");
    window->ExpireEntry = yon_gtk_builder_get_widget(builder,"ExpireEntry");
    window->ExpireButton = yon_gtk_builder_get_widget(builder,"ExpireButton");
    window->CancelButton = yon_gtk_builder_get_widget(builder,"CancelButton");
    window->AddButton = yon_gtk_builder_get_widget(builder,"AddButton");
    window->PasswordEntry = yon_gtk_builder_get_widget(builder,"PasswordEntry");
    window->PasswordButton = yon_gtk_builder_get_widget(builder,"PasswordButton");

    yon_gtk_entry_block_symbols(GTK_ENTRY(window->EmailEntry),"()\'\"&^%$#!*=\\|?><~`:;,[]{}");
    yon_gtk_entry_block_symbols(GTK_ENTRY(window->NameEntry),"()\'\"&^%$#@!+*=\\|?><~`:;,[]{}");

    // yon_gtk_entry_set_password_visibility_icon(GTK_ENTRY(window->PasswordConfirmationEntry));
    yon_gtk_entry_set_password_visibility_icon(GTK_ENTRY(window->PasswordEntry));

    g_signal_connect(G_OBJECT(window->ExpireCombo),"changed",G_CALLBACK(yon_gtk_widget_set_sensitive_from_combo_box),window->ExpireButton);
    g_signal_connect(G_OBJECT(window->ExpireCombo),"changed",G_CALLBACK(yon_gtk_widget_set_sensitive_from_combo_box),window->ExpireEntry);
    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
    g_signal_connect(G_OBJECT(window->ExpireButton),"clicked",G_CALLBACK(on_calendar_open),window);
    g_signal_connect(G_OBJECT(window->AddButton),"clicked",G_CALLBACK(on_key_generate_accept),window);
    g_signal_connect(G_OBJECT(window->PasswordButton),"clicked",G_CALLBACK(on_key_password_clicked),window);

    int size;
    config_str encription_keys = yon_resource_open_file(key_encription_path,&size);
    window->expire_time=0;

    for (int i=1;i<size;i++){
        yon_char_remove_last_symbol(encription_keys[i],'\n');
        int parsed_size;
        config_str parsed = yon_char_parse(encription_keys[i],&parsed_size,";");
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(window->EncryptionCombo),parsed[2],parsed[0]);
        yon_char_parsed_free(parsed,parsed_size);
    }
    gtk_combo_box_set_active_id(GTK_COMBO_BOX(window->EncryptionCombo),"RSA");
    return window;
}

void on_key_clicked(GtkWidget *self, main_window *widgets){
    key_creation_window *window = yon_key_creation_window_new();
    yon_gtk_window_setup(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->Window),KEY_CREATION_TITLE_LABEL,icon_path,"key-create-window");
        gtk_label_set_text(GTK_LABEL(window->HeadLabel),KEY_CREATION_TITLE_LABEL);
    gtk_widget_show(window->Window);
}



void on_sign_window_accept(GtkWidget *self, dictionary *dict){
    main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
    sign_window *window = yon_dictionary_get_data(dict->first->next,sign_window*);
    GtkTreeModel *model;
    GtkTreeIter iter;
    if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->ReposTree)),&model,&iter)){
        char *arch;
        char *repo;
        char *storage;
        char *signature = (char*)gtk_combo_box_get_active_id(GTK_COMBO_BOX(window->SignCombo));
        gtk_tree_model_get(GTK_TREE_MODEL(widgets->RepoList),&iter,3,&arch,-1);
        char *full_path = yon_char_new(arch);
        repo = yon_char_divide(arch,yon_char_find_last(arch,'/'));
        storage = yon_char_divide(repo,yon_char_find_last(repo,'/'));
        storage = yon_char_append(storage,"/");
        GList *list = gtk_tree_selection_get_selected_rows(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->RepoFileTree)),NULL);
        char *targets = "";
        for (int i=0;i<g_list_length(list);i++){
            char *pack;
            gtk_tree_model_get_iter(GTK_TREE_MODEL(widgets->RepoFileList),&iter,(GtkTreePath*)g_list_nth_data(list,i));
            gtk_tree_model_get(GTK_TREE_MODEL(widgets->RepoFileList),&iter,2,&pack,-1);
            char *temp = yon_char_unite(targets, " ", full_path,"/",pack,NULL);
            if (!yon_char_is_empty(targets)) free(targets);
            targets=temp;
        }
        if (!system(yon_debug_output("%s\n",yon_sign_package(storage,repo,arch,targets,signature)))){
            yon_ubl_status_box_render(SIGN_SUCCESS_LABEL,BACKGROUND_IMAGE_SUCCESS_TYPE);
        } else {
            yon_ubl_status_box_render(SIGN_FAIL_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);

        }
            on_subwindow_close(window->Window);
    }
    yon_interface_update(widgets);
}

sign_window *yon_sign_window_new(){
    sign_window *window = malloc(sizeof(sign_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_sign);

    window->Window = yon_gtk_builder_get_widget(builder,"MainWindow");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->HeadLabel = yon_gtk_builder_get_widget(builder,"HeadLabel");
    window->SignCombo = yon_gtk_builder_get_widget(builder,"SignCombo");
    window->CancelButton = yon_gtk_builder_get_widget(builder,"CancelButton");
    window->SignButton = yon_gtk_builder_get_widget(builder,"SignButton");

    g_signal_connect(G_OBJECT(window->CancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);

    return window;
}

void on_packages_sign(GtkWidget *self, main_window *widgets){
    sign_window *window = yon_sign_window_new();
    yon_gtk_window_setup(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->Window),SIGNATURE_TITLE_LABEL,icon_path,"sign-window");
    yon_combo_box_text_set_signs(GTK_COMBO_BOX_TEXT(window->SignCombo));
    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->SignButton),"clicked",G_CALLBACK(on_sign_window_accept),dict);
    gtk_widget_show(window->Window);
}