#include "upac-gtk.h"

typedef struct {
    GtkWidget *MainBox;
    GtkWidget *InfoTree;
    GtkListStore *InfoList;
} info_element;
info_element *yon_package_info_element_new();
void yon_gtk_label_set_font(GtkLabel *label);

void yon_gtk_label_set_font(GtkLabel *label){
    g_return_if_fail(GTK_IS_LABEL(label));
    PangoAttrList *attributes = pango_attr_list_new();
    PangoFontDescription *font_descr = pango_font_description_new();
    pango_font_description_set_family(font_descr,"Source Code Pro 10");
    PangoAttribute *font_attr = pango_attr_font_desc_new(font_descr);
    pango_attr_list_insert(attributes,font_attr);
    gtk_label_set_attributes(GTK_LABEL(label),attributes);
}

info_element *yon_package_info_element_new(){
    info_element *element = malloc(sizeof(info_element));
    memset(element,0,sizeof(info_element));
    GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_package_info);
    element->MainBox = yon_gtk_builder_get_widget(builder,"MainBox");
    element->InfoTree = yon_gtk_builder_get_widget(builder,"InfoTree");
    element->InfoList = GTK_LIST_STORE(gtk_builder_get_object(builder,"InfoList"));
 
    return element;
}

yon_window *yon_package_info_window_create(const char *package_str){
    if (yon_char_is_empty(package_str)) return NULL;
    yon_window *window = yon_window_new();
    yon_gtk_window_setup(GTK_WINDOW(window->Window),NULL,PACKAGE_INFO_LABEL,icon_path,"info-label");
    int size=0;
    char *package = yon_char_new(package_str);
    if (strstr(package,",")){
        char *temp = yon_char_replace(package,","," ");
        free(package);
        package = temp;
    }
    
    GtkWidget *label = NULL;
    yon_packages_info *info_struct = yon_packages_get_info_struct(YON_PACKAGES_ALL,package);
    if (!info_struct) return NULL;
    char* info_string = yon_packages_get_info_string(info_struct);
    yon_debug_output("%s\n",info_string);
    config_str info = yon_char_parse(info_string,&size,"\n");
    if (size>0){
        info_element *element = yon_package_info_element_new();
        gtk_box_pack_start(GTK_BOX(window->MainBox),element->MainBox,1,1,0);
        for (int i=0;i<size;i++){
            yon_char_remove_last_symbol(info[i],'\n');
            GtkTreeIter iter;
            int parsed_size;
            config_str parsed = yon_char_parse(info[i],&parsed_size,":");
            gtk_list_store_append(element->InfoList,&iter);
            gtk_list_store_set(element->InfoList,&iter,0,parsed[0],1,!yon_char_is_empty(parsed[1])?_(parsed[1]):"",-1);
            
        }
    } else {
        label = gtk_label_new(PACKAGE_NOT_FOUND_LABEL);
        yon_gtk_label_set_font(GTK_LABEL(label));
        gtk_widget_show(label);
        gtk_box_pack_start(GTK_BOX(window->MainBox),label,0,0,0);
        gtk_label_set_xalign(GTK_LABEL(label),0);
    }
    gtk_widget_show(window->Window);
    return window;
}