#include "ubinstall-gtk.h"


void on_log_closed(GtkWidget *, log_window *window){

    GtkWidget *button = g_object_get_data(G_OBJECT(window->Window),"button");
    gtk_widget_set_sensitive(button,1);

    free(window->command);
    window->Window=NULL;
}

gboolean on_log_window_exit(GtkWidget *,GdkEvent*, log_window *window){
    if (window->timer_id){
        g_source_remove(window->timer_id);
        window->timer_id=0;
    }
    return 0;
}

log_window *yon_log_window_new(){
    log_window *window = malloc(sizeof(log_window));
    memset(window,0,sizeof(log_window));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_log_view);
    window->Window = yon_gtk_builder_get_widget(builder,"MainWindow");
    window->ScrollWindow = yon_gtk_builder_get_widget(builder,"ScrollWindow");
    window->HeadLabel = yon_gtk_builder_get_widget(builder,"headerTopic");
    window->LogTextView = yon_gtk_builder_get_widget(builder,"LogTextView");
    window->StatusBox = yon_gtk_builder_get_widget(builder,"StatusBox");
    window->ScrollToEndCheck = yon_gtk_builder_get_widget(builder,"ScrollToEndCheck");
    window->monitor = NULL;
    g_signal_connect(G_OBJECT(window->ScrollWindow),"scroll-child",G_CALLBACK(yon_log_scroll),window);
    g_signal_connect(G_OBJECT(window->Window),"delete-event",G_CALLBACK(on_log_window_exit),window);
    
    gtk_widget_show(window->Window);
    return window;
}

gboolean yon_log_scroll(log_window *window){
    GtkAdjustment *adj = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(window->ScrollWindow));
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->ScrollToEndCheck))){
        gtk_adjustment_set_value(adj,
            gtk_adjustment_get_upper(adj));
    }
    return G_SOURCE_CONTINUE;
}

void yon_read_log(GFileMonitor *,GFile *,GFile *,GFileMonitorEvent ,log_window *window){
        if (window->Window){
            int size;
            g_mutex_lock(&main_config.progress_mutex);
            config_str parsed = yon_file_open(window->command,&size);
            g_mutex_unlock(&main_config.progress_mutex);
            if (size){
                char *final = yon_char_parsed_to_string(parsed,size,"");
                GtkTextIter start_iter, end_iter;
                gtk_text_buffer_get_start_iter(gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->LogTextView)),&start_iter);
                gtk_text_buffer_get_end_iter(gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->LogTextView)),&end_iter);
                gtk_text_buffer_delete(gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->LogTextView)),&start_iter,&end_iter);
                gtk_text_buffer_set_text(gtk_text_view_get_buffer(GTK_TEXT_VIEW(window->LogTextView)),final,strlen(final));
                if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->ScrollToEndCheck))){
                    if (!window->timer_id){
                        window->timer_id = g_idle_add((GSourceFunc)yon_log_scroll,window);
                    }
                    gtk_adjustment_set_value(gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(window->ScrollWindow)),gtk_adjustment_get_upper(gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(window->ScrollWindow))));
                } else if (window->timer_id){
                    g_source_remove(window->timer_id);
                    window->timer_id=0;
                }
                free(final);
                yon_char_parsed_free(parsed,size);
            }
            g_mutex_lock(&main_config.install_mutex);
            if (!main_config.install_complete){
                g_mutex_unlock(&main_config.install_mutex);
                return;
            } else {
                g_mutex_unlock(&main_config.install_mutex);
                gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(window->ScrollToEndCheck),0);
                gtk_widget_set_sensitive(window->ScrollToEndCheck,0);
                if (window->timer_id){
                    g_source_remove(window->timer_id);
                    window->timer_id=0;
                }
            }
        }
    return ;
}

void on_process_log_view(GtkWidget *,main_window *widgets){
    log_window *window = yon_log_window_new();
    g_object_set_data(G_OBJECT(window->Window),"widgets",widgets);
    g_object_set_data(G_OBJECT(window->Window),"button",widgets->ReadFullLogButton);
    g_signal_connect(G_OBJECT(window->Window),"destroy",G_CALLBACK(on_log_closed),window);
    gtk_widget_set_sensitive(widgets->ReadFullLogButton,0);
    yon_gtk_window_setup(GTK_WINDOW(window->Window),NULL,INSTALL_LOG_LABEL,icon_path,"log_viewer");
    window->command = yon_char_new(short_log_path);
    GFile *file = g_file_new_for_path(window->command);
    GError *err = NULL;
    window->monitor = g_file_monitor_file(file,G_FILE_MONITOR_NONE,NULL,&err);
    if (err){
        printf("%s\n",err->message);
    }
    g_signal_connect(G_OBJECT(window->monitor),"changed",G_CALLBACK(yon_read_log),window);
    g_object_unref(file);
    yon_read_log(NULL,NULL,NULL,G_FILE_MONITOR_EVENT_CHANGED,window);
}

void on_summary_log_view(GtkWidget *,main_window *widgets){
    log_window *window = yon_log_window_new();
    g_object_set_data(G_OBJECT(window->Window),"widgets",widgets);
    g_object_set_data(G_OBJECT(window->Window),"button",widgets->ReadShortLogButton);
    g_signal_connect(G_OBJECT(window->Window),"destroy",G_CALLBACK(on_log_closed),window);
    gtk_widget_set_sensitive(widgets->ReadShortLogButton,0);
    yon_gtk_window_setup(GTK_WINDOW(window->Window),NULL,PROGRESS_LOG_LABEL,icon_path,"log_viewer");
    window->command = yon_char_new(full_log_path);
    GFile *file = g_file_new_for_path(window->command);
    window->monitor = g_file_monitor_file(file,G_FILE_MONITOR_NONE,NULL,NULL);
    g_signal_connect(G_OBJECT(window->monitor),"changed",G_CALLBACK(yon_read_log),window);
    g_object_unref(file);
    yon_read_log(NULL,NULL,NULL,G_FILE_MONITOR_EVENT_CHANGED,window);
}

void yon_installation_progress_update(GFileMonitor *,GFile *,GFile *,GFileMonitorEvent ,main_window *widgets) {
    int size=0;

    g_mutex_lock(&main_config.progress_mutex);
    config_str text = yon_file_open(progress_path, &size);
    if (!text||!size){ 
        g_mutex_unlock(&main_config.progress_mutex);    
        return;
    }

    g_mutex_unlock(&main_config.progress_mutex);

    if (size&&text) {
        if (!yon_char_is_empty(text[size-1]) && text[size-1][0] == '(') {
            char *current_copy = yon_char_new(text[size-1]);
            char *percentage = yon_char_divide_search(current_copy, ")", -1);

            if (!strstr(percentage, "#pb")) {
                double fraction = atof(percentage+1);
                gtk_label_set_text(GTK_LABEL(widgets->InstallationLabel), current_copy);
                gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(widgets->InstallationProgress), fraction / 100);
                gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(widgets->PackageInstallationProgress), 0);
                gtk_label_set_text(GTK_LABEL(widgets->PackageInstallationLabel), "");
                if (!yon_char_is_empty(current_copy)) free(current_copy);
            } else {
                gtk_widget_show(gtk_widget_get_parent(widgets->PackageInstallationProgress));

                config_str parsed = yon_char_parse(current_copy, &size, " ");
                if (size >= 3) {
                    double fraction = atof(parsed[3]) / 100;
                    gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(widgets->PackageInstallationProgress), fraction);
                    gtk_label_set_text(GTK_LABEL(widgets->PackageInstallationLabel), yon_char_parsed_to_string(parsed, size, " "));
                }
                if (!yon_char_is_empty(current_copy)) free(current_copy);
            }

        }
        size=0;
        text=NULL;
    }
}

gboolean yon_progress_bar_start(main_window *widgets){
    GFile *file_desc = g_file_new_for_path(progress_path);
    GError *err = NULL;
    widgets->install_info_monitor = g_file_monitor_file(file_desc,G_FILE_MONITOR_NONE,NULL,&err);
    if (err){
        printf("%s\n",err->message);
        yon_ubl_status_box_spawn(GTK_CONTAINER(widgets->StatusBox),err->message,5,BACKGROUND_IMAGE_FAIL_TYPE);
        return G_SOURCE_REMOVE;
    }
    g_signal_connect(G_OBJECT(widgets->install_info_monitor),"changed",G_CALLBACK(yon_installation_progress_update),widgets);
    g_object_unref(file_desc);
    if (access(progress_path,F_OK)){
        FILE *file = fopen(progress_path,"w");
        if (file){
            fclose(file);
        }
    }
    return G_SOURCE_REMOVE;
}