#include "upac-gtk.h"

config main_config;

//functions

void yon_config_init(){
    main_config.pacman_table = g_hash_table_new(g_str_hash,g_str_equal);
}

void on_install_activate(GtkWidget *, main_window *widgets){
    int install_size = 0;
    config_str install_parameters = NULL;
    int remove_size = 0;
    config_str remove_parameters = NULL;
    char *ubur_install_package_string = NULL;
    {
        int modules_install_size = 0;
        config_str modules_install_packages = yon_modules_get_install_packages(&modules_install_size,widgets);
        int modules_remove_size = 0;
        config_str modules_remove_packages = yon_modules_get_remove_packages(&modules_remove_size,widgets);

        int groups_install_size = 0;
        config_str groups_install_packages = yon_groups_get_install_packages(&groups_install_size,widgets);
        int groups_remove_size = 0;
        config_str groups_remove_packages = yon_groups_get_remove_packages(&groups_remove_size,widgets);

        int pacman_install_size = 0;
        config_str pacman_install_packages = yon_pacman_get_install_packages(&pacman_install_size,widgets);
        int pacman_remove_size = 0;
        config_str pacman_remove_packages = yon_pacman_get_remove_packages(&pacman_remove_size,widgets);

        int desktop_install_size = 0;
        config_str desktop_install_packages = yon_desktop_get_install_packages(&desktop_install_size,widgets);
        int desktop_remove_size = 0;
        config_str desktop_remove_packages = yon_desktop_get_remove_packages(&desktop_remove_size,widgets);

        int ubur_install_size = 0;
        config_str ubur_install_packages = yon_ubur_get_install_packages(&ubur_install_size,widgets);
        if (ubur_install_size==-1){
            gtk_notebook_set_current_page(GTK_NOTEBOOK(widgets->MainNotebook),YON_PAGE_UBUR);
            yon_ubl_status_highlight_incorrect(widgets->UburSourceButton);
            return;
        }
        int ubur_remove_size = 0;
        config_str ubur_remove_packages = yon_ubur_get_remove_packages(&ubur_remove_size,widgets);
        if (ubur_remove_size==-1){
            return;
        }

        install_size = 0;
        install_parameters = yon_char_parsed_merge_stack(&install_size,modules_install_size,modules_install_packages,
                                    groups_install_size,groups_install_packages,
                                    pacman_install_size,pacman_install_packages,
                                    desktop_install_size,desktop_install_packages,
                                    -1);
        remove_size = 0;
        remove_parameters = yon_char_parsed_merge_stack(&remove_size,modules_remove_size,modules_remove_packages,
                                    groups_remove_size,groups_remove_packages,
                                    ubur_remove_size,ubur_remove_packages,
                                    pacman_remove_size,pacman_remove_packages,
                                    desktop_remove_size,desktop_remove_packages,
                                    -1);

        ubur_install_package_string = yon_char_parsed_to_string(ubur_install_packages,ubur_install_size," ");
        
        // if (modules_install_size) yon_char_parsed_free(modules_install_packages,modules_install_size);
        // if (modules_remove_size) yon_char_parsed_free(modules_remove_packages,modules_remove_size);
        // if (groups_install_size) yon_char_parsed_free(groups_install_packages,groups_install_size);
        // if (groups_remove_size) yon_char_parsed_free(groups_remove_packages,groups_remove_size);
        // if (pacman_install_size) yon_char_parsed_free(pacman_install_packages,pacman_install_size);
        // if (pacman_remove_size) yon_char_parsed_free(pacman_remove_packages,pacman_remove_size);
        // if (ubur_install_size) yon_char_parsed_free(ubur_install_packages,ubur_install_size);
        // if (ubur_remove_size) yon_char_parsed_free(ubur_remove_packages,ubur_remove_size);

    }

    char *install_parameters_full = yon_char_parsed_to_string(install_parameters,install_size," ");
    char *remove_parameters_full = yon_char_parsed_to_string(remove_parameters,remove_size," ");
    if (yon_char_is_empty(install_parameters_full)&&yon_char_is_empty(remove_parameters_full)){
        yon_ubl_status_box_render(NOTHING_TO_CHANGE_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
        return;
    }
    char *install_command_full = NULL;
    if (!yon_char_is_empty(install_parameters_full)) install_command_full = install_command(install_parameters_full);
    char *remove_command_full = NULL;
    if (!yon_char_is_empty(remove_parameters_full)) remove_command_full = remove_command(remove_parameters_full);
    char *ubur_install_command_full = NULL;
    if (!yon_char_is_empty(ubur_install_package_string)) ubur_install_command_full = ubur_install_command(ubur_install_package_string);

    int commands_size=0;
    config_str commands_parsed = yon_char_parsed_new(&commands_size, yon_char_return_if_exist(install_command_full,""), yon_char_return_if_exist(remove_command_full,""), yon_char_return_if_exist(ubur_install_command_full,""),NULL);
    __attribute_maybe_unused__ char *full_command = yon_char_parsed_to_string(commands_parsed,commands_size,";");
    yon_command_execute_async(full_command,widgets);
    gtk_widget_show(widgets->TerminalBox);
}

gboolean yon_interface_update(main_window *widgets){
    yon_ubl_status_box_render(UPDATE_START_LABEL,BACKGROUND_IMAGE_INFO_TYPE);
    main_config.pacman_finished=0;
    main_config.ubur_finished=0;
    yon_groups_tab_init(widgets);
    yon_module_init(widgets);
    g_thread_new("pacman_fill_thread",(GThreadFunc)yon_pacman_fill,widgets);
    g_thread_new("ubur_fill_thread",(GThreadFunc)yon_ubur_fill,widgets);
    yon_desktop_init(widgets);
    return G_SOURCE_REMOVE;
}
// standard functions

gboolean on_page_switch(GtkWidget *, GtkWidget *, int page,main_window *widgets){
    g_object_ref(G_OBJECT(widgets->MainRepoStatusBox));
    GtkWidget *parent = gtk_widget_get_parent(widgets->MainRepoStatusBox);
    gtk_container_remove(GTK_CONTAINER(parent),widgets->MainRepoStatusBox);
    gtk_widget_show(widgets->UncheckAllCheck);
    switch(page){
        case YON_PAGE_GROUPS:
            gtk_box_pack_start(GTK_BOX(widgets->GroupsRepoStatusBox),widgets->MainRepoStatusBox,0,0,0);
        break;
        case YON_PAGE_MODULES:
            gtk_box_pack_start(GTK_BOX(widgets->ModulesRepoStatusBox),widgets->MainRepoStatusBox,0,0,0);
        break;
        case YON_PAGE_PACKAGES:
            gtk_box_pack_start(GTK_BOX(widgets->PackagesRepoStatusBox),widgets->MainRepoStatusBox,0,0,0);
            gtk_widget_hide(widgets->UncheckAllCheck);
        break;
        case YON_PAGE_UBUR:
            gtk_box_pack_start(GTK_BOX(widgets->UburRepoStatusBox),widgets->MainRepoStatusBox,0,0,0);

        break;
        case YON_PAGE_DESKTOP:
            gtk_box_pack_start(GTK_BOX(widgets->DesktopRepoStatusBox),widgets->MainRepoStatusBox,0,0,0);
            gtk_widget_hide(widgets->UncheckAllCheck);

        break;
        default:
            gtk_box_pack_start(GTK_BOX(widgets->GroupsRepoStatusBox),widgets->MainRepoStatusBox,0,0,0);
    }
    
    int active = 0;
    switch(page){
        case YON_PAGE_GROUPS:
            active = yon_tree_model_check_boolean(GTK_TREE_MODEL(widgets->PackagesList),0,1);
        break;
        case YON_PAGE_MODULES:
            active = yon_module_check_selected(widgets);
        break;
        case YON_PAGE_PACKAGES:
            active = yon_tree_model_check_boolean(GTK_TREE_MODEL(widgets->PacmanFilter),0,1);
        break;
        case YON_PAGE_UBUR:
            active = yon_ubur_check_selected(widgets);

        break;
        // case YON_PAGE_DESKTOP:

        break;
        default: break;

    }
    switch(active){
        case 1: gtk_button_set_label(GTK_BUTTON(widgets->UncheckAllCheck),UNCHECK_ALL_LABEL);
                g_object_set_data(G_OBJECT(widgets->UncheckAllCheck),"uncheck",widgets);

        break;
        case 0: gtk_button_set_label(GTK_BUTTON(widgets->UncheckAllCheck),CHECK_ALL_LABEL);
                g_object_set_data(G_OBJECT(widgets->UncheckAllCheck),"uncheck",NULL);
    }
    return 0;
}


void yon_switch_all_update(main_window *widgets){
    int active = 0;
    switch((enum YON_PAGES)gtk_notebook_get_current_page(GTK_NOTEBOOK(widgets->MainNotebook))){
        case YON_PAGE_GROUPS:
            active = yon_tree_model_check_boolean(GTK_TREE_MODEL(widgets->PackagesList),0,1);
        break;
        case YON_PAGE_MODULES:
            active = yon_module_check_selected(widgets);
        break;
        case YON_PAGE_PACKAGES:
            active = yon_tree_model_check_boolean(GTK_TREE_MODEL(widgets->PacmanFilter),0,1);
        break;
        case YON_PAGE_UBUR:
            active = yon_ubur_check_selected(widgets);

        break;
        // case YON_PAGE_DESKTOP:

        break;
        default: break;

    }
    switch(active){
        case 1: gtk_button_set_label(GTK_BUTTON(widgets->UncheckAllCheck),UNCHECK_ALL_LABEL);
                g_object_set_data(G_OBJECT(widgets->UncheckAllCheck),"uncheck",widgets);

        break;
        case 0: gtk_button_set_label(GTK_BUTTON(widgets->UncheckAllCheck),CHECK_ALL_LABEL);
                g_object_set_data(G_OBJECT(widgets->UncheckAllCheck),"uncheck",NULL);
    }
}

void on_switch_all_check(GtkWidget *,main_window *widgets){
    g_signal_handlers_block_by_func(G_OBJECT(widgets->UncheckAllCheck),G_CALLBACK(on_switch_all_check),widgets);
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widgets->UncheckAllCheck),0);
    g_signal_handlers_unblock_by_func(G_OBJECT(widgets->UncheckAllCheck),G_CALLBACK(on_switch_all_check),widgets);
    switch((enum YON_PAGES)gtk_notebook_get_current_page(GTK_NOTEBOOK(widgets->MainNotebook))){
        case YON_PAGE_GROUPS:
            yon_groups_switch_all(widgets);
        break;
        case YON_PAGE_MODULES:
            yon_modules_switch_all(widgets);
        break;
        case YON_PAGE_PACKAGES:
            yon_pacman_switch_all(widgets);
        break;
        case YON_PAGE_UBUR:
            yon_ubur_switch_all(widgets);
        break;
        // case YON_PAGE_DESKTOP:
        //     yon_desktop_switch_all(widgets);
        // break;
        default: break;
    }
    yon_switch_all_update(widgets);
}

/**yon_main_window_complete(main_window *widgets) 
 * [EN] 
 *  
 * [RU] 
 * Функция настройки основного окна приложения. [widgets] - структура со стандартным интерфейсом. 
*/ 
main_window *yon_main_window_complete(main_window *widgets){ 
    widgets = yon_remalloc(widgets,sizeof(main_window)); 
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path); 
    gtk_box_pack_start(GTK_BOX(widgets->InterfaceBox),yon_gtk_builder_get_widget(builder,"BoxMain"),1,1,0); 
    // Custom widgets configuration 
    {
        widgets->MainOverlay = yon_gtk_builder_get_widget(builder,"MainOverlay");
        widgets->MainNotebook = yon_gtk_builder_get_widget(builder,"MainNotebook");
        widgets->InstallButton = yon_gtk_builder_get_widget(builder,"InstallButton");
        widgets->MainRepoStatusBox = yon_gtk_builder_get_widget(builder,"MainRepoStatusBox");
        widgets->PackagesStatusImage = yon_gtk_builder_get_widget(builder,"PackagesStatusImage");
        widgets->PackagesStatusSpinner = yon_gtk_builder_get_widget(builder,"PackagesStatusSpinner");
        widgets->PackagesStatusLabel = yon_gtk_builder_get_widget(builder,"PackagesStatusLabel");
        widgets->PackagesStatusButton = yon_gtk_builder_get_widget(builder,"PackagesStatusButton");
        widgets->GroupsRepoStatusBox = yon_gtk_builder_get_widget(builder,"GroupsRepoStatusBox");
        widgets->ModulesRepoStatusBox = yon_gtk_builder_get_widget(builder,"ModulesRepoStatusBox");
        widgets->PackagesRepoStatusBox = yon_gtk_builder_get_widget(builder,"PackagesRepoStatusBox");
        widgets->DesktopRepoStatusBox = yon_gtk_builder_get_widget(builder,"DesktopRepoStatusBox");
        widgets->PackagesTree = yon_gtk_builder_get_widget(builder,"PackagesTree");
        widgets->PackagesChosenCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"PackagesChosenCell"));
        widgets->AdditionalComponentsList = yon_gtk_builder_get_widget(builder,"AdditionalComponentsList");
        widgets->PacmanTree = yon_gtk_builder_get_widget(builder,"PacmanSoftwareAllPackagesTree");
        widgets->UburComponentsList = yon_gtk_builder_get_widget(builder,"UburComponentsList");
        widgets->UburRepoStatusBox = yon_gtk_builder_get_widget(builder,"UburRepoStatusBox");
        widgets->UburSourceLabel = yon_gtk_builder_get_widget(builder,"UburSourceLabel");
        widgets->UburSourceButton = yon_gtk_builder_get_widget(builder,"UburSourceButton");
        widgets->PacmanChosenCell = GTK_CELL_RENDERER(gtk_builder_get_object(builder,"PacmanChosenCell"));
        widgets->DesktopFlow = yon_gtk_builder_get_widget(builder,"DesktopFlow");
        widgets->UncheckAllCheck = yon_gtk_builder_get_widget(builder,"UncheckAllCheck");
        widgets->OverallSizeLabel = yon_gtk_builder_get_widget(builder,"OverallSizeLabel");
        widgets->TerminalProgress = yon_gtk_builder_get_widget(builder,"TerminalProgress");
        widgets->TerminalCancelButton = yon_gtk_builder_get_widget(builder,"TerminalCancelButton");
        widgets->TerminalMoreButton = yon_gtk_builder_get_widget(builder,"TerminalMoreButton");
        widgets->TerminalRevealer = yon_gtk_builder_get_widget(builder,"TerminalRevealer");
        // widgets->TerminalPaned = yon_gtk_builder_get_widget(builder,"TerminalPaned");
        widgets->InstallTerminal = yon_gtk_builder_get_widget(builder,"InstallTerminal");
        widgets->TerminalBox = yon_gtk_builder_get_widget(builder,"TerminalBox");
        widgets->SizeHandleEvent = yon_gtk_builder_get_widget(builder,"SizeHandleEvent");
        widgets->PacmanTree = yon_gtk_builder_get_widget(builder,"PacmanTree");
        widgets->PacmanSearchEntry = yon_gtk_builder_get_widget(builder,"PacmanSearchEntry");
        widgets->PacmanChosenButton = yon_gtk_builder_get_widget(builder,"PacmanChosenButton");
        widgets->PackagesList = GTK_TREE_STORE(gtk_builder_get_object(builder,"Packages"));
        widgets->PacmanList = GTK_LIST_STORE(gtk_builder_get_object(builder,"PacmanList"));
        widgets->PacmanFilter = GTK_TREE_MODEL(gtk_builder_get_object(builder,"PacmanFilter"));

        GError *err = NULL;
        GFile *file_desc = g_file_new_for_path(pacman_lock_dir_path);
        widgets->db_lock_monitor = g_file_monitor_directory(file_desc,G_FILE_MONITOR_NONE,NULL,&err);
        if (err){
            printf("%s\n",err->message);
        }
        g_signal_connect(G_OBJECT(widgets->db_lock_monitor),"changed",G_CALLBACK(yon_db_lock_update),widgets);
        g_signal_connect(G_OBJECT(widgets->db_lock_monitor),"changed",G_CALLBACK(yon_db_unlock_update),widgets);
        g_signal_connect(G_OBJECT(widgets->PackagesStatusButton),"clicked",G_CALLBACK(on_status_button_update),widgets);
        g_signal_connect(G_OBJECT(widgets->MainNotebook),"switch-page",G_CALLBACK(on_page_switch),widgets);
        g_signal_connect(G_OBJECT(widgets->TerminalMoreButton),"clicked",G_CALLBACK(on_more_clicked),widgets);
        g_signal_connect(G_OBJECT(widgets->PacmanChosenCell),"toggled",G_CALLBACK(on_pacman_toggled),widgets);
        g_signal_connect(G_OBJECT(widgets->PacmanSearchEntry),"changed",G_CALLBACK(on_filter_changed),widgets);
        g_signal_connect(G_OBJECT(widgets->PacmanChosenButton),"clicked",G_CALLBACK(on_pacman_open),widgets);
        g_signal_connect(G_OBJECT(widgets->PackagesChosenCell),"toggled",G_CALLBACK(yon_on_groups_chosen),widgets);
        g_signal_connect(G_OBJECT(widgets->UncheckAllCheck),"toggled",G_CALLBACK(on_switch_all_check),widgets);
        g_signal_connect(G_OBJECT(widgets->InstallButton),"clicked",G_CALLBACK(on_install_activate),widgets);
        g_signal_connect(G_OBJECT(widgets->Window),"check-resize",G_CALLBACK(on_window_resize),widgets);
        g_signal_connect(G_OBJECT(widgets->InstallTerminal),"child-exited",G_CALLBACK(on_command_execute_success),widgets);
        g_signal_connect(G_OBJECT(widgets->TerminalCancelButton),"clicked",G_CALLBACK(on_terminal_cancel),widgets);

        g_signal_connect(G_OBJECT(widgets->UburSourceButton),"clicked",G_CALLBACK(on_ubur_source_clicked),widgets);
    }
    gtk_overlay_set_overlay_pass_through(GTK_OVERLAY(widgets->MainOverlay),widgets->TerminalRevealer,1);
    yon_terminal_init(widgets);
    char *path = yon_char_unite(yon_ubl_user_get_home_directory(),"/.config/",LocaleName,"/",LocaleName,".conf",NULL);
    yon_window_config_load(path);
    free(path);
    gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(widgets->PacmanFilter),(GtkTreeModelFilterVisibleFunc)yon_filter,widgets,NULL);

    gtk_tree_view_set_search_column(GTK_TREE_VIEW(widgets->PacmanTree),1);

    yon_root_button_setup((template_main_window*)widgets,main_config.launch_arguments,main_config.launch_size);
        on_status_button_update(NULL,widgets);
    yon_switch_all_update(widgets);
    yon_size_update(widgets);
    GList *list = gtk_container_get_children(GTK_CONTAINER(gtk_window_get_titlebar(GTK_WINDOW(widgets->Window))));
    GList *iter;
    for (iter=list;iter;iter=iter->next){
        if (GTK_IS_BOX(iter->data)){
            GList *chlist = gtk_container_get_children(GTK_CONTAINER(iter->data));
            if (chlist->next){
                gtk_widget_hide(GTK_WIDGET(chlist->data));
            } else {
                gtk_widget_hide(GTK_WIDGET(iter->data));
            }
        }
    }
    return widgets;
}

int main(int argc, char *argv[]){ 
    setlocale(LC_ALL, "");
    textdomain (LocaleName);
    
    yon_config_init();
    yon_ubl_connect_config((_template_config*)&main_config); 
    yon_ubl_window_init(TITLE_LABEL,TITLE_INFO_LABEL,LocaleName,CssPath,LocaleName,version_application,WIKI_LINK);
	config_str unfound = NULL;
	int size=0;
	yon_ubl_setup_arguments(argc,argv,&unfound,&size,NULL);
    gtk_init(&argc,&argv);
    template_main_window *widgets = yon_ubl_window_setup(); 

    main_config.launch_arguments=yon_char_parsed_copy(argv,argc);
    main_config.launch_size=argc;
    yon_packages_option_use_full_path_set(1);
    yon_packages_init();
    yon_main_window_complete((main_window*)widgets);
    
    gtk_main();
    return 0;
}