#include "libublsettingsui-gtk3.h"

_template_config *template_config = NULL;
template_app_info template_app_information;

static char *__yon_config_mode=NULL;


void __yon_config_init();

char *yon_char_get_localised_from_lib(char *string){
    textdomain(template_ui_LocaleName);
    char *ret = _(string);
    textdomain(template_app_information.app_locale);
    return ret;
}

char *yon_ubl_save_mode_get_icon_name(SAVE_MODE_TYPE type){
    switch (type){
        case SAVE_MODE_FULL:
            return "com.ublinux.libublsettingsui-gtk3.config-changes-symbolic";
            break;
        case SAVE_MODE_MODULE:
            return "com.ublinux.libublsettingsui-gtk3.config-module-symbolic";
            break;
        case SAVE_MODE_SANDBOX:
            return "com.ublinux.libublsettingsui-gtk3.config-sandbox-symbolic";
            break;
        case SAVE_MODE_RAM_HOME:
            return "com.ublinux.libublsettingsui-gtk3.config-sandbox-ram-home-symbolic";
            break;
        case SAVE_MODE_HDD:
            return "com.ublinux.libublsettingsui-gtk3.config-sandbox-hdd-symbolic";
            break;
        case SAVE_MODE_HDD_HOME:
            return "com.ublinux.libublsettingsui-gtk3.config-sandbox-hdd-home-symbolic";
            break;
    }
}

SAVE_MODE_TYPE yon_ubl_save_mode_get_type(char *type){
    if (!strcmp(type,"changes")){
        return SAVE_MODE_FULL;
    }
    if (!strcmp(type,"module")){
        return SAVE_MODE_MODULE;
    }
    if (!strcmp(type,"sandbox")){
        return SAVE_MODE_SANDBOX;
    }
    if (!strcmp(type,"sandbox_ram_home")){
        return SAVE_MODE_RAM_HOME;
    }
    if (!strcmp(type,"sandbox_hdd")){
        return SAVE_MODE_HDD;
    }
    if (!strcmp(type,"sandbox_hdd_home")){
        return SAVE_MODE_HDD_HOME;
    }
}

//signal emmit handlers - no header initialization

void yon_open_browser(GtkWidget *self, char *link){
    GtkWidget *window = yon_ubl_browser_window_open(link,template_app_information.app_title);
    if (window)
    gtk_window_set_icon_name(GTK_WINDOW(window),yon_char_append("com.ublinux.",template_app_information.app_tech_name));
}

void on_open_documentation_confirmation(GtkWidget *self, char *link){
    textdomain(template_ui_LocaleName);
    if (template_app_information.always_open_documentation==0){
        GtkBuilder *builder = gtk_builder_new_from_resource(ui_glade_path_documentation);
        template_documentation_confirmation_window *window = malloc(sizeof(template_documentation_confirmation_window));
        window->Window = yon_gtk_builder_get_widget(builder,"helpConfirmationWindow");
        window->AcceptButton = yon_gtk_builder_get_widget(builder,"ReadHelpButton");
        window->CloseButton = yon_gtk_builder_get_widget(builder,"CancelHelpButton");
        window->HeaderLabel = yon_gtk_builder_get_widget(builder,"webHeaderNameLabel");
        window->AlwaysOpenCheck = yon_gtk_builder_get_widget(builder,"AlwaysOpenDocumentationCheckbox");
        gtk_label_set_text(GTK_LABEL(window->HeaderLabel),template_app_information.app_title);
        gtk_window_set_title(GTK_WINDOW(window->Window),template_app_information.app_title);
        gtk_window_set_icon_name(GTK_WINDOW(window->Window),yon_char_append("com.ublinux.",template_app_information.app_tech_name));
        gtk_widget_show_all(window->Window);
        g_signal_connect(G_OBJECT(window->CloseButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
        textdomain(template_app_information.app_locale);
        g_signal_connect(G_OBJECT(window->AcceptButton),"clicked",G_CALLBACK(yon_open_browser),yon_char_new(_(link)));
        textdomain(template_ui_LocaleName);
        g_signal_connect(G_OBJECT(window->AcceptButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
        
    } else {
        textdomain(template_app_information.app_locale);
        yon_open_browser(self,_(link));
        textdomain(template_ui_LocaleName);
    }
    textdomain(template_app_information.app_locale);
}

/**on_link(GtkWidget *self, char* uri, gpointer user_data)
 * [EN]
 * Signal for hadnling AboutDialog links.
 * Connect to "activate-link" signal.
 * [self] is AboutDialog window;
 * [uri] is activated link;
 * [user_data] is pointer for user data, hasn't used in standard handler;
 * [RU]
 * Функция для обработки сигнала нажатия на ссылку окна AboutDialog.
 * Присоединять к сигналу "activate-link".
 * [self] - окно AboutDialog;
 * [uri] - ссылка, по которой совершается переход;
 * [user_data] - указатель на любые другие данные, не используется в стандартном обработчике;
*/
void on_link(GtkWidget *self, char* uri, gpointer user_data){
    gtk_widget_destroy(self);
    on_open_documentation_confirmation(self,uri);
}

void on_about(GtkWidget *self, char *version_application){
    GtkBuilder *builder=gtk_builder_new_from_resource(ui_glade_path_about);
    GtkWidget *window=yon_gtk_builder_get_widget(builder,"AboutWindow");
    GtkWidget *title=yon_gtk_builder_get_widget(builder,"headerAboutTopic");
    GtkWidget *hideButtonBox=yon_gtk_builder_get_widget(builder,"buttonBoxHide");
    gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(window),version_application);
    gtk_about_dialog_set_comments(GTK_ABOUT_DIALOG(window),template_app_information.app_title);
    gtk_about_dialog_set_logo_icon_name(GTK_ABOUT_DIALOG(window),yon_char_append("com.ublinux.",template_app_information.app_tech_name));
    gtk_window_set_icon_name(GTK_WINDOW(window),yon_char_append("com.ublinux.",template_app_information.app_tech_name));
    char *title_str = about_label(template_app_information.app_title);
    gtk_about_dialog_set_program_name(GTK_ABOUT_DIALOG(window),template_app_information.app_tech_name);
    gtk_label_set_text(GTK_LABEL(title),template_app_information.app_title);
    g_signal_connect(G_OBJECT(window),"activate-link",G_CALLBACK(on_link),NULL);
    gtk_widget_set_visible(hideButtonBox,0);
    gtk_widget_destroy(hideButtonBox);
    gtk_window_set_title(GTK_WINDOW(window),title_str);
    gtk_widget_show(window);
}

//functions


int yon_confirmation_dialog_call(GtkWidget *self,dialog_confirmation_data *data){
    textdomain(template_ui_LocaleName);
    GtkWindow *parent = NULL;
    if (self)
        parent = GTK_WINDOW(gtk_widget_get_toplevel(self));
    GtkWidget *dialog = gtk_dialog_new_with_buttons(template_app_information.app_title,parent,GTK_DIALOG_USE_HEADER_BAR,CANCEL_LABEL,GTK_RESPONSE_CANCEL,ACCEPT_LABEL,GTK_RESPONSE_ACCEPT,NULL);
    textdomain(template_app_information.app_locale);
    gtk_window_set_modal(GTK_WINDOW(dialog),1);
    gtk_window_set_icon_name(GTK_WINDOW(dialog),yon_char_append("com.ublinux.",template_app_information.app_tech_name));
    gtk_window_set_title(GTK_WINDOW(dialog),template_app_information.app_title);
    gtk_widget_set_size_request(dialog,450,-1);
    GList *list = gtk_container_get_children(GTK_CONTAINER(gtk_dialog_get_header_bar(GTK_DIALOG(dialog))));
    GtkWidget *image_cancel = gtk_image_new_from_icon_name("com.ublinux.libublsettingsui-gtk3.cancel-symbolic",GTK_ICON_SIZE_BUTTON);
    GtkWidget *image_accept = gtk_image_new_from_icon_name("com.ublinux.libublsettingsui-gtk3.accept-symbolic",GTK_ICON_SIZE_BUTTON);
    gtk_button_set_image((GtkButton*)g_list_nth_data(list,0),image_cancel);
    gtk_button_set_image((GtkButton*)g_list_nth_data(list,1),image_accept);
    gtk_style_context_add_class(gtk_widget_get_style_context((GtkWidget*)g_list_nth_data(list,0)),"marginright");
    gtk_style_context_add_class(gtk_widget_get_style_context((GtkWidget*)g_list_nth_data(list,1)),"marginright");

    g_list_free(list);
    GtkWidget *header_label = gtk_label_new(yon_char_is_empty(data->title)?template_app_information.app_title:data->title);
    gtk_widget_show(header_label);
    PangoAttrList *attributes = pango_attr_list_new();
    PangoAttribute *boldAttr = pango_attr_weight_new(PANGO_WEIGHT_BOLD);
    pango_attr_list_insert(attributes, boldAttr);
    gtk_label_set_attributes(GTK_LABEL(header_label),attributes);

    GtkWidget *header = gtk_dialog_get_header_bar(GTK_DIALOG(dialog));
    gtk_header_bar_set_custom_title(GTK_HEADER_BAR(header),header_label);
    gtk_widget_show(header);

    GtkWidget *image = gtk_image_new_from_icon_name("dialog-question-symbolic",GTK_ICON_SIZE_DIALOG);
    gtk_widget_show(image);
    gtk_widget_set_margin_start(image,20);
    gtk_widget_set_margin_end(image,20);
    gtk_widget_set_margin_bottom(image,20);
    gtk_widget_set_margin_top(image,20);

    GtkWidget *label = gtk_label_new("");
    gtk_widget_set_margin_end(label,20);
    gtk_widget_show(label);
    gtk_label_set_line_wrap_mode(GTK_LABEL(label),PANGO_WRAP_WORD);
    gtk_label_set_line_wrap(GTK_LABEL(label),1);
    gtk_label_set_markup(GTK_LABEL(label),data->action_text);

    GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,5);
    gtk_widget_show(box);
    gtk_box_pack_start(GTK_BOX(box),image,0,0,5);
    gtk_box_pack_start(GTK_BOX(box),label,0,0,5);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))),box,1,1,5);

    gtk_window_set_default_size(GTK_WINDOW(dialog),450,-1);

    int resp = gtk_dialog_run(GTK_DIALOG(dialog));
    if (resp == GTK_RESPONSE_ACCEPT){
        if (data->function){
            data->function(NULL,data->data);
        }
    } else resp=0;
    gtk_widget_destroy(dialog);
    return resp;
}

dialog_confirmation_data *yon_confirmation_dialog_data_new(){
    dialog_confirmation_data *data = new(dialog_confirmation_data);
    data->action_text=NULL;
    data->data=NULL;
    data->function=NULL;
    data->title=NULL;
    return data;
}

char* yon_debug_output(char *pattern,char*text){
    if (template_config->debug_mode){
        printf(pattern,text);
    }
    return text;
}

// standard functions

char *yon_get_default_label_with_parameter(char *command){
    int size;
    config_str parsed = yon_config_load(command,&size);
    if (strcmp(parsed[0],"(null)\n")){
        if (parsed){
            yon_char_remove_last_symbol(parsed[0],'\n');
            char *default_string = yon_char_unite(DEFAULT_LABEL," ","(",parsed[0],")",NULL);
            return default_string;
        }
    }
    return DEFAULT_LABEL;
}

int yon_ubl_connect_config(_template_config *config){
    int replaces;
    if(!template_config)
        replaces=0;
    else
        replaces=1;
    template_config = config;
    __yon_config_init();
    return replaces;
}

gboolean on_window_delete (GtkWidget *self, GdkEvent *,template_main_window *){
    template_saving_window *window = yon_exit_window_new();
    if (window){
        GCallback delete_callback = g_object_get_data(G_OBJECT(self),"exit_data_callback");
        if (delete_callback){
            ((void(*)(template_saving_window*))delete_callback)(window);
            GtkTreeIter iter;
            if (!gtk_tree_model_get_iter_first(GTK_TREE_MODEL(window->list),&iter)){
                gtk_widget_destroy(window->Window);
                free(window);
                return 0;
            }
        }
        gtk_widget_show(window->Window);
        return 1;
    }
    return 0;
}

void yon_window_remove_exit_config_check(template_main_window *widgets){
    g_signal_handlers_disconnect_by_func(G_OBJECT(widgets->Window),G_CALLBACK(on_window_delete),NULL);
}

void yon_window_set_exit_config_check(template_main_window *widgets, GCallback data_callback_function){
    g_signal_connect(G_OBJECT(widgets->Window),"delete-event",G_CALLBACK(on_window_delete),NULL);
    g_object_set_data(G_OBJECT(widgets->Window),"exit_data_callback",data_callback_function);
}

template_main_window *setup_window(){
    /* Widgets getting | Получение виджетов */
    template_main_window *widgets = malloc(sizeof(template_main_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(ui_glade_path);
    widgets->Window = yon_gtk_builder_get_widget(builder,"MainWindow");
    widgets->HeadLabel = yon_gtk_builder_get_widget(builder,"headerTopic");
    widgets->PlugBox = yon_gtk_builder_get_widget(builder,"plugBox");

    widgets->HeadOverlay = yon_gtk_builder_get_widget(builder,"HeadOverlay");
    widgets->HeadImage = yon_gtk_builder_get_widget(builder,"HeadImage");
    widgets->HeadBox = yon_gtk_builder_get_widget(builder,"HeaderBox");
    widgets->HeadTitleLabel = yon_gtk_builder_get_widget(builder,"HeaderTitleLabel");
    widgets->HeadInfoLabel = yon_gtk_builder_get_widget(builder,"HeaderInfoLabel");
    
    widgets->StatusBox = yon_gtk_builder_get_widget(builder,"mainStatusBox");
    widgets->StatusIcon = yon_gtk_builder_get_widget(builder,"mainStatusIcon");
    widgets->StatusLabel = yon_gtk_builder_get_widget(builder,"mainStatusLabel");

    widgets->SaveMenuItem = yon_gtk_builder_get_widget(builder,"SaveGlobalLocalConfigurationMenuItem");
    widgets->SaveGlobalMenuItem = yon_gtk_builder_get_widget(builder,"SaveGlobalConfigurationMenuItem");
    widgets->SaveLocalMenuItem = yon_gtk_builder_get_widget(builder,"SaveLocalConfigurationMenuItem");
    widgets->SaveCustomMenuItem = yon_gtk_builder_get_widget(builder,"SaveExternalConfigurationMenuItem");
    widgets->RightBox = yon_gtk_builder_get_widget(builder,"HeaderRightBox");

    widgets->LoadGlobalMenuItem = yon_gtk_builder_get_widget(builder,"LoadGlobalConfigurationMenuItem");
    widgets->LoadLocalMenuItem = yon_gtk_builder_get_widget(builder,"LoadLocalConfigurationMenuItem");
    widgets->LoadCustomMenuItem = yon_gtk_builder_get_widget(builder,"LoadExternalConfigurationMenuItem");
    widgets->LeftBox = yon_gtk_builder_get_widget(builder,"HeaderLeftBox");

    widgets->InterfaceBox = yon_gtk_builder_get_widget(builder,"InterfaceBox");
    GtkWidget *HatIcon = yon_gtk_builder_get_widget(builder,"HatIcon");
    GtkWidget *ModeStatusImage = yon_gtk_builder_get_widget(builder,"ModeStatusImage");

    widgets->DocumentationMenuItem = yon_ubl_menu_item_documentation_new(DOCUMENTATION_LABEL);
    widgets->AboutMenuItem = yon_ubl_menu_item_about_new(ABOUT_LABEL);


    if (template_config->lock_load_global == 1){
        gtk_widget_set_sensitive(widgets->LoadGlobalMenuItem,0);
    }
    if (template_config->lock_save_global == 1){
        gtk_widget_set_sensitive(widgets->SaveGlobalMenuItem,0);
        gtk_widget_set_sensitive(widgets->SaveMenuItem,0);
    }
    if (template_config->lock_save_local == 1){
        gtk_widget_set_sensitive(widgets->SaveLocalMenuItem,0);
        gtk_widget_set_sensitive(widgets->SaveMenuItem,0);
    }
    if (template_config->lock_load_system == 1){
        gtk_widget_set_sensitive(widgets->LoadLocalMenuItem,0);
    }
    
    char *icon_name = yon_char_append("com.ublinux.",template_app_information.app_tech_name);
    gtk_window_set_icon_name(GTK_WINDOW(widgets->Window),icon_name);
    gtk_image_set_from_icon_name(GTK_IMAGE(widgets->HeadImage),icon_name,GTK_ICON_SIZE_BUTTON);
    gtk_image_set_pixel_size(GTK_IMAGE(widgets->HeadImage),32);
    gtk_image_set_from_icon_name(GTK_IMAGE(HatIcon),icon_name,GTK_ICON_SIZE_BUTTON);
    gtk_image_set_pixel_size(GTK_IMAGE(HatIcon),64);
    gtk_window_set_title(GTK_WINDOW(widgets->Window),template_app_information.app_title);
    gtk_label_set_text(GTK_LABEL(widgets->HeadLabel),template_app_information.app_title);
    gtk_label_set_text(GTK_LABEL(widgets->HeadTitleLabel),template_app_information.app_title);
    gtk_label_set_text(GTK_LABEL(widgets->HeadInfoLabel),template_app_information.app_description);
    
    GtkWidget *menu = yon_gtk_builder_get_widget(builder,"menu2");
    gtk_menu_shell_append(GTK_MENU_SHELL(menu),widgets->DocumentationMenuItem);
    gtk_menu_shell_append(GTK_MENU_SHELL(menu),widgets->AboutMenuItem);

    /* Widget registration for config monitoring | Регистрация виджетов для мониторинга конфига */
    // yon_window_config_add_listener(widgets->HeadInfoLabel,"head-text","label",YON_TYPE_STRING); 

    /* Signal connection | Присоединение сигналов */
    g_signal_connect(G_OBJECT(widgets->Window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    g_signal_connect(G_OBJECT(widgets->DocumentationMenuItem),"activate",G_CALLBACK(on_open_documentation_confirmation),template_app_information.wiki_link);
    g_signal_connect(G_OBJECT(widgets->AboutMenuItem),"activate",G_CALLBACK(on_about),template_app_information.app_version);
    g_signal_connect(G_OBJECT(widgets->Window),"delete-event",G_CALLBACK(on_window_delete),NULL);
    
    if (yon_char_is_empty(__yon_config_mode)){
        int size;
        config_str cnf = yon_config_load(SAVE_MODE_GET_COMMAND,&size);
        if (cnf){
            __yon_config_mode=yon_char_new(cnf[0]);
            if (__yon_config_mode[strlen(__yon_config_mode)-1]=='\n') __yon_config_mode[strlen(__yon_config_mode)-1]='\0';
            yon_char_parsed_free(cnf,size);
            if (!yon_char_is_empty(__yon_config_mode)&&strcmp(__yon_config_mode,"(null)")){
                gtk_image_set_from_pixbuf(GTK_IMAGE(ModeStatusImage),gtk_icon_theme_load_icon_for_scale(gtk_icon_theme_get_default(),yon_ubl_save_mode_get_icon_name(yon_ubl_save_mode_get_type(__yon_config_mode)),25,1,GTK_ICON_LOOKUP_FORCE_SIZE,NULL));
                char *tooltip_text=NULL;
                switch (yon_ubl_save_mode_get_type(__yon_config_mode)){
                    case SAVE_MODE_FULL: tooltip_text = SAVE_MODE_FULL_LABEL;
                        break;
                    case SAVE_MODE_MODULE: tooltip_text = SAVE_MODE_MODULE_LABEL;
                        break;
                    case SAVE_MODE_SANDBOX: tooltip_text = SAVE_MODE_SANDBOX_LABEL;
                        break;
                    case SAVE_MODE_RAM_HOME: tooltip_text = SAVE_MODE_RAM_HOME_LABEL;
                        break;
                    case SAVE_MODE_HDD: tooltip_text = SAVE_MODE_HDD_LABEL;
                        break;
                    case SAVE_MODE_HDD_HOME: tooltip_text = SAVE_MODE_HDD_HOME_LABEL;
                        break;
                }
                gtk_widget_set_tooltip_text(ModeStatusImage,tooltip_text);
            } else {
                free(__yon_config_mode);
                __yon_config_mode=NULL;
                gtk_widget_hide(ModeStatusImage);
            }
        } else {
            gtk_widget_hide(ModeStatusImage);
        }
    }
    gtk_widget_show(widgets->Window);
    return widgets;
}
void __yon_on_size_changed(GtkWindow *self, GtkScrolledWindow *target){
    int x,y;
    gtk_window_get_size(self,&x,&y);
    if (x<800)
        gtk_scrolled_window_set_policy(target,GTK_POLICY_AUTOMATIC,GTK_POLICY_AUTOMATIC);
    else 
        gtk_scrolled_window_set_policy(target,GTK_POLICY_NEVER,GTK_POLICY_AUTOMATIC);
}

void yon_gtk_scrolled_window_set_horizontal_at_desired_size(GtkWidget *window, GtkScrolledWindow *target){
    g_signal_connect(G_OBJECT(window),"check-resize",G_CALLBACK(__yon_on_size_changed),target);
}

template_app_info yon_ubl_get_app_info(){
    return template_app_information;
}

int yon_ubl_window_init(char *app_title, char *app_description, char *locale, char *css, char *tech_name, char *version, char *wiki){
    bind_textdomain_codeset (locale,"UTF-8");
    bind_textdomain_codeset (template_ui_LocaleName,"UTF-8");
    template_app_information.app_title=app_title;
    template_app_information.css_path=css;
    template_app_information.app_tech_name=tech_name;
    template_app_information.app_version=version;
    template_app_information.wiki_link=wiki;
    template_app_information.app_description=app_description;
    
    template_app_information.app_locale=locale;
}

int yon_ubl_setup_arguments(int argc, char *argv[],config_str *unfound_arguments, int *arguments_size, char *additional_options_output){
    (*arguments_size)=0;
    int option_index=0; 
    int show_help=0; 
    int debug_mode=0; 
    { 
        struct option long_options[] = {
            {"help", 0, 0, 'h'},
            {"version", 0, 0, 'V'},
            {"lock-help", 0,0, 1},
            {"lock-save", 0,0, 2},
            {"lock-save-local", 0,0, 3},
            {"lock-save-global", 0,0, 4},
            {"lock-load-global", 0,0, 5},
            {"lock-load-local", 0,0, 6},
            {"socket-id", 1, 0, 's'},
            {"socket-ext-id", 1,0, 'e'},
            {"socket-trd-id", 1,0, 't'},
            {"clear-config", 0,0, 'c'}, 
            {"debug", 0,0, 'd'},
            {"config", 1, 0, 'f'},
            { NULL, 0, NULL, 0 } 
        };
        config_str unregistered_arguments=NULL;
        for (int i=1;i<argc;i++){ 
            int argument=getopt_long(argc,argv,"hVvs:e:t:cdf:",long_options,&option_index); 
            switch(argument){ 
                case 'h': 
                    show_help=1; 
                    break; 
                case 'v': 
                case 'V': 
                    printf("%s\n",VERSION_LABEL); 
                    exit(0); 
                    break; 
                case 's': 
                    if(optarg) 
                        template_config->socket_id=atoi(optarg); 
                    break; 
                case 'e': 
                    if(optarg) 
                        template_config->save_socket_id=atoi(optarg); 
                    break; 
                case 't': 
                    if(optarg) 
                        template_config->load_socket_id=atoi(optarg); 
                    break; 
                case 'c': 
                    {
                        char *path = yon_char_unite(yon_ubl_user_get_home_directory(),"/.config/",template_app_information.app_tech_name,"/",NULL);
                        struct passwd *user = getpwnam(yon_ubl_root_user_get());
                        if (chown(path,user->pw_uid,user->pw_gid)){};
                        if (system(remove_config_dir_command)){}; 
                    }
                    break;
                case 'd': template_config->debug_mode=1; 
                    break;
                case 1: 
                    template_config->lock_help=1; 
                    break; 
                case 2: 
                    template_config->lock_save_local=1; 
                    template_config->lock_save_global=1; 
                    break; 
                case 3: 
                    template_config->lock_save_local=1; 
                    break; 
                case 4: 
                    template_config->lock_save_global=1; 
                    break; 
                case 5: 
                    template_config->lock_load_global=1; 
                    break; 
                case 6: 
                    template_config->lock_load_system=1; 
                    break; 
                case 'f':
                    template_config->force_ini = yon_char_new(optarg);
                    template_config->config_load_path = template_config->force_ini;
                    template_config->config_save_path = template_config->force_ini;
                    break;
                default:
                    char *unfound = optarg;
                    yon_char_parsed_add_or_create_if_exists(unregistered_arguments,arguments_size,yon_char_unite(argv[i],!yon_char_is_empty(unfound)?"=":"",!yon_char_is_empty(unfound)?unfound:"",NULL));
            } 
        } 
        if (arguments_size)yon_char_parsed_add_or_create_if_exists(unregistered_arguments,arguments_size,NULL);
        (*unfound_arguments)=unregistered_arguments;
        if (show_help&&!template_config->lock_help){ 
            printf("%s\n",HELP_LABEL(additional_options_output)); 
            exit(0); 
            } 
    } 
 
    if (getuid()!=0){ 
        template_config->lock_load_global=1; 
        template_config->lock_save_global=1; 
        template_config->lock_save_local=1; 
    } 
}


void on_root_get_root(char *argline){
    yon_launch(argline);
}

int arg_size;
config_str arg_target;

void on_root_access(GtkWidget *, GtkWidget *window){
    if (getuid()){
        char *argline = arg_target[0];
        for (int i=1;i<arg_size;i++){
            if (yon_char_check_begins_with(arg_target[i],"--socket-id")||yon_char_check_begins_with(arg_target[i],"--socket-ext-id")||yon_char_check_begins_with(arg_target[i],"--socket-trd-id")){ i++;
                continue;
            }
            char *temp = yon_char_unite(argline," ", arg_target[i],NULL);
            if(strcmp(argline,"")&&strcmp(argline,template_app_information.app_tech_name))
                free(argline);
            argline=temp;
        }
        if (getuid()!=0){
            argline = yon_char_unite("setsid /usr/bin/bash -c 'pkexec ",argline,"'; exit",NULL);
            printf("%s\n",argline);
            pthread_t thread_id;
            pthread_create(&thread_id, NULL, (void *)on_root_get_root,argline);
            gtk_widget_destroy(window);
            // exit(0);
            gtk_main_quit();
        }
    }
}

void yon_root_button_init(GtkWidget *root_item,GtkWindow *window){
    g_signal_connect(G_OBJECT(root_item),"activate", G_CALLBACK(on_root_access),window);

}

GtkWidget *yon_root_button_new(config_str args, int args_size){
    textdomain(template_ui_LocaleName);
    arg_size=args_size;
    arg_target=args;
    GtkWidget *root_item = gtk_menu_item_new();
    gtk_style_context_add_class(gtk_widget_get_style_context(root_item),"menuitemtop");
    GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,5);
    GtkWidget *root_label = gtk_label_new(ROOT_CHECK_LABEL);
    GtkWidget *root_check = gtk_check_button_new();
    g_object_set_data(G_OBJECT(root_item),"Label",root_label);
    gtk_box_pack_start(GTK_BOX(box),root_check,0,0,0);
    gtk_box_pack_start(GTK_BOX(box),root_label,1,1,0);
    gtk_container_add(GTK_CONTAINER(root_item),box);
    gtk_widget_show_all(root_item);
    if (getuid()==0) {
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(root_check),1);
        gtk_widget_set_sensitive(root_item,0);
    }
    textdomain(template_app_information.app_locale);
    return root_item;
}

void on_debug_switch(GtkWidget *self, GtkWidget *check){
    template_config->debug_mode = !template_config->debug_mode;
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check),template_config->debug_mode);
}

GtkWidget *yon_debug_button_new(){
    textdomain(template_ui_LocaleName);
    GtkWidget *debug_item = gtk_menu_item_new();
    gtk_style_context_add_class(gtk_widget_get_style_context(debug_item),"menuitemtop");
    GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,5);
    GtkWidget *debug_label = gtk_label_new(DEBUG_CHECK_LABEL);
    GtkWidget *debug_check = gtk_check_button_new();
    g_object_set_data(G_OBJECT(debug_item),"Label",debug_label);
    gtk_box_pack_start(GTK_BOX(box),debug_check,0,0,0);
    gtk_box_pack_start(GTK_BOX(box),debug_label,1,1,0);
    gtk_container_add(GTK_CONTAINER(debug_item),box);
    gtk_label_set_xalign(GTK_LABEL(debug_label),0);
    gtk_widget_show_all(debug_item);
    if (template_config->debug_mode) {
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(debug_check),1);
    }
    textdomain(template_app_information.app_locale);
    g_signal_connect(G_OBJECT(debug_item),"activate", G_CALLBACK(on_debug_switch),debug_check);
    gtk_widget_show_all(debug_item);
    return debug_item;
}

void yon_root_button_setup(template_main_window *widgets, config_str args, int args_size){
    GtkWidget *root_item = yon_root_button_new(args,args_size);
    gtk_style_context_add_class(gtk_widget_get_style_context(widgets->DocumentationMenuItem),"menuitemmiddle");
    gtk_style_context_remove_class(gtk_widget_get_style_context(widgets->DocumentationMenuItem),"menuitemtop");
    gtk_menu_shell_prepend(GTK_MENU_SHELL(gtk_widget_get_parent(widgets->DocumentationMenuItem)),root_item);
    g_signal_connect(G_OBJECT(root_item),"activate", G_CALLBACK(on_root_access),widgets->Window);
}

void __yon_config_init(){ 
    template_config->always_open_documentation=0; 
    template_config->socket_id=-1; 
    template_config->save_socket_id=-1; 
    template_config->load_socket_id=-1; 
    template_config->lock_help=0; 
    template_config->lock_help=0; 
    template_config->lock_load_global=0; 
    template_config->lock_save_global=0; 
    template_config->lock_save_local=0; 
    template_config->load_mode=YON_CONFIG_LOCAL;
}

template_main_window *yon_ubl_window_setup(){
    textdomain (template_ui_LocaleName);
    // setlocale(LC_ALL,"");
    template_main_window *widgets = setup_window();
    textdomain(template_ui_LocaleName);
    if (yon_ubl_status_box_setup(widgets->StatusIcon,widgets->StatusBox,widgets->StatusLabel)){
        if (getuid()!=0)
            yon_ubl_status_box_render(ROOT_WARNING_LABEL,BACKGROUND_IMAGE_FAIL_TYPE);
        else
            yon_ubl_status_box_render(LOCAL_LOAD_SUCCESS_LABEL,BACKGROUND_IMAGE_SUCCESS_TYPE);
    }
    textdomain(template_app_information.app_locale);
    template_config->load_mode=YON_CONFIG_LOCAL;
    if(template_config)
        yon_ubl_setup_sockets(widgets->PlugBox,widgets->LeftBox,widgets->RightBox,template_config->socket_id,template_config->load_socket_id,template_config->save_socket_id);
    yon_window_config_setup(GTK_WINDOW(widgets->Window));
    GtkCssProvider *css=gtk_css_provider_new();
    gtk_css_provider_load_from_resource(css,template_app_information.css_path);
    gtk_style_context_add_provider_for_screen(gdk_screen_get_default(),
                            GTK_STYLE_PROVIDER(css),
                            -1);
    GtkCssProvider *css_lib=gtk_css_provider_new();
    gtk_css_provider_load_from_resource(css_lib,"/com/ublinux/css/libublsettingsui-gtk3.css");
    gtk_style_context_add_provider(gtk_widget_get_style_context(widgets->HeadBox),GTK_STYLE_PROVIDER(css_lib),GTK_STYLE_PROVIDER_PRIORITY_USER);

    return widgets;
}

void yon_on_email_check(GtkEntry *self,GdkEventFocus *event,GtkContainer *status){
    char *text = (char*)gtk_entry_get_text(self);
    if (!strstr(text,"@")){
        yon_ubl_status_box_spawn(status,EMAIL_INVALID_LABEL,0,BACKGROUND_IMAGE_FAIL_TYPE);
    } else {
        yon_ubl_status_box_despawn(status);
    }
}

void yon_on_space_first_changed(GtkEntry *editable){
    const char *text = gtk_entry_get_text(editable);
    gchar *new_text = yon_char_new(text);
    if (new_text[0]==' ') free(yon_char_divide(new_text,0));

    if (strlen(new_text) < strlen(text)) {
        g_signal_handlers_block_by_func(editable, G_CALLBACK(yon_on_space_first_changed), NULL);
        gtk_entry_set_text(editable, new_text);
        g_signal_handlers_unblock_by_func(editable, G_CALLBACK(yon_on_space_first_changed), NULL);
        g_signal_stop_emission_by_name(editable, "changed");
    }

    g_free(new_text);
}

void yon_on_digit_only_changed(GtkEditable *editable, const gchar *text, gint length, gint *position){
    gchar *new_text = g_new(gchar, length + 1);
    gint i, j = 0;

    for (i = 0; i < length; i++) {
        if (text[i]>'0'&&text[i]<'9') {
            new_text[j] = text[i];
            j++;
        }
    }
    if (j < length) {
        g_signal_handlers_block_by_func(editable, G_CALLBACK(yon_on_digit_only_changed), NULL);
        gtk_editable_insert_text(editable, new_text, j, position);
        g_signal_handlers_unblock_by_func(editable, G_CALLBACK(yon_on_digit_only_changed), NULL);
        g_signal_stop_emission_by_name(editable, "insert-text");
    }

    g_free(new_text);
}

void yon_on_path_check(GtkEntry *self,GdkEventFocus *event,GtkContainer *status){
    char *text = (char*)gtk_entry_get_text(self);
    if (text[0]=='~'){
        text = yon_char_new(text);
        free(yon_char_divide(text,0));
        char *new_text = yon_char_unite(yon_ubl_user_get_home_directory(),"/",text,NULL);
        free(text);
        gtk_entry_set_text(GTK_ENTRY(self),new_text);
        text = new_text;
    }
    if (!strstr(text,"/")){
        yon_ubl_status_box_spawn(status,PATH_INVALID_LABEL,0,BACKGROUND_IMAGE_FAIL_TYPE);
    } else {
        yon_ubl_status_box_despawn(status);
    }

}

char *yon_gtk_entry_check_restricted(GtkEntry *target){
    GtkInputPurpose purpose = gtk_entry_get_input_purpose(target);
    const char *text = gtk_entry_get_text(target);
    char *error=NULL;
    if (!yon_char_is_empty(text)){
        switch(purpose){
            case GTK_INPUT_PURPOSE_EMAIL:{
                char *temp = NULL;
                if (!((temp = strstr(text,"@"))&&
                strstr(temp,".")&&
                strlen(temp)!=strlen(text)&&
                temp[1]!='.'&&
                strstr(temp,".")[1]!='\0')){
                    error = yon_char_get_localised_from_lib(EMAIL_INVALID_LABEL);
                }
            }
            break;
            case GTK_INPUT_PURPOSE_URL:{
                if (!strstr(text,"/")){
                    error = yon_char_get_localised_from_lib(PATH_INVALID_LABEL);
                }
            }
            break;
            default: break;
        }
    }
    return error;
    
}

void yon_entry_set_entry_type(GtkEntry *target,GtkBox *status){
    GtkInputPurpose purpose = gtk_entry_get_input_purpose(target);
            g_signal_connect(G_OBJECT(target),"changed",G_CALLBACK(yon_on_space_first_changed),NULL);
    switch(purpose){

        case GTK_INPUT_PURPOSE_DIGITS:
            g_signal_connect(G_OBJECT(target),"insert-text",G_CALLBACK(yon_on_digit_only_changed),NULL);

        break;
        case GTK_INPUT_PURPOSE_EMAIL:
            yon_gtk_entry_block_symbols(target,"/'\"\\+=)(*&>?<^%$#!:;?,)");
            yon_gtk_entry_block_languages(target);
            break;
        case GTK_INPUT_PURPOSE_NAME:
        case GTK_INPUT_PURPOSE_URL:
            yon_gtk_entry_block_restricted_symbols(target);

        break;
        default: break;
    }
}

yon_window *yon_window_new(){
    yon_window *window = new(yon_window);
    memset(window,0,sizeof(yon_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(ui_glade_path_window);

    window->Window = yon_gtk_builder_get_widget(builder,"Window");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->MainBox = yon_gtk_builder_get_widget(builder,"MainBox");

    return window;
}