#include "controller.h"
#include "var.h"

void pars_flag(int index_start, int argc, char* argv[]);

int main(int argc, char** argv) {
    string str_argv= "";
    string str_cmd_argv = "";
    for (int i=1; i<argc; i++){
        str_cmd_argv+= to_string(*argv[i]) + " ";
    }
    if (geteuid()!=0){
        string cmd = "";
        cmd = cmd + "pkexec " + app_name + " " + str_cmd_argv;
        return system(cmd.c_str());
    }
    if (argc > 1){
        str_argv = argv[1];
    }
    bindtextdomain(app_name, "/usr/share/locale/");
    bind_textdomain_codeset(app_name, "UTF-8");
    textdomain(app_name);
    if (str_argv.find("--socket-id") != std::string::npos) {
        auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example.plug");
        auto builder = Gtk::Builder::create_from_file(path_glade);
        Glib::init();
        setlocale(LC_ALL, "");
        Glib::OptionContext context;
    
        CmdArgParser parser{
            "Socket ID",
            "Command line argument for socket ID communication.",
            "No help available, sorry"
        };

        context.set_main_group(parser);
        context.parse(argc, argv); 

        ::Window socketID = parser.GetSocketID();

        // Handle plug:
        SettingsPlug plug{socketID, builder};
        plug.show();
    
        app->run(plug);
        return 0;
    }
    else if (str_argv.find("-") != std::string::npos || argc == 1) {
        int len_argv = 1;
        auto app = Gtk::Application::create(len_argv, argv, "org.gtkmm.example.plug");
        auto builder = Gtk::Builder::create_from_file(path_glade);
        pars_flag(1, argc, argv);
        Controller* wnd = nullptr;
        builder->get_widget_derived("window", wnd);
        auto r = app->run(*wnd);
        delete wnd;
        return r;
    }
}

void pars_flag(int index_start, int argc, char* argv[]) {
    string str_argv = "";
    for (int i = index_start; i<argc; i++){
        str_argv = argv[i];
        if (str_argv == "--help" || str_argv == "-h"){
            help();
            exit(1);
        }
        else if (str_argv == "--version" || str_argv == "-v"){
            string version = string(str_version) + version_application + "\n";
            cout << version.c_str();
            exit(1);
        }
        else if (str_argv == "--lock-help") {
            flag_lock_help = true;
        }
        else if (str_argv == "--lock-save") {
            flag_save = true;
            flag_save_local = true;
            flag_save_global = true;
        }
        else if (str_argv == "--lock-save-local"){
            flag_save_local = true;
        }
        else if (str_argv == "--lock-save-global"){
            flag_save_global = true;
        }
        else if (str_argv == "--lock-load-global"){
            flag_load_global = true;
        }
        else{
            if (index_start == 1){
                g_print(no_recognized);
            }
        }
        
            
    }
}