#include "libublsettings-gtk3.h"

int yon_calendar_set_orientation = 0;

int yon_calendar_last_date = 0;

int yon_calendar_get_last_date(){
    return yon_calendar_last_date;
}

void yon_calendar_set_date_orientation(int orientation){
    yon_calendar_set_orientation = orientation;
}

void yon_on_date_selected(GtkWidget *self,GtkWidget *target){
    {
        if (self){};
        unsigned int year=0, month=0, day=0;
        gtk_calendar_get_date(GTK_CALENDAR(self),&year,&month,&day);
        char *dy = yon_char_from_int(day);
        char *mn = yon_char_from_int(month+1);
        char *yr = yon_char_from_int(year);
        if (month+1<10) mn = yon_char_append("0",mn);
        if (day<10) dy = yon_char_append("0",dy);

        GDateTime *datetime = g_date_time_new_now_local();
        GDateTime *current_datetime = g_date_time_new_local(year,month+1,day,0,0,0);
        int comparison = g_date_time_compare(current_datetime,datetime);
        if ((comparison <0&&yon_calendar_set_orientation>0)||(comparison>0&&yon_calendar_set_orientation<0)){
            gtk_entry_set_text(GTK_ENTRY(target),g_date_time_format(datetime,"%Y-%m-%d"));
            yon_calendar_last_date = g_date_time_to_unix(datetime);
        } else {
            char *date_string = yon_char_unite(yr,"-",mn,"-",dy,NULL);
            gtk_entry_set_text(GTK_ENTRY(target), date_string);
            yon_calendar_last_date = g_date_time_to_unix(current_datetime);
        }
        free(dy);
        free(mn);
        free(yr);
    }
}

void yon_on_popover_closed(GtkWidget *self){
    gtk_widget_destroy(self);
}

void yon_calendar_popover_open(GtkEntry *TargetEntry,GtkWidget *PopupTarget){
    g_return_if_fail(GTK_IS_ENTRY(TargetEntry));
    g_return_if_fail(GTK_IS_WIDGET(PopupTarget));
    GtkWidget *popover = gtk_popover_new(PopupTarget);
    GtkWidget *calendar = gtk_calendar_new();
    gtk_container_add(GTK_CONTAINER(popover),calendar);
    gtk_widget_show_all(popover);
    gtk_popover_popup(GTK_POPOVER(popover));

    const char *date_str = gtk_entry_get_text(TargetEntry);
    if (date_str&&strcmp(date_str,"")){
        int date_size;
        config_str date_parsed = yon_char_parse((char*)date_str,&date_size,"-");
        gtk_calendar_select_day(GTK_CALENDAR(calendar),atoi(date_parsed[2]));
        gtk_calendar_select_month(GTK_CALENDAR(calendar),atoi(date_parsed[1])-1,atoi(date_parsed[0]));
    }
    
    g_signal_connect(G_OBJECT(calendar),"day-selected",G_CALLBACK(yon_on_date_selected),TargetEntry);
    g_signal_connect(G_OBJECT(popover),"closed",G_CALLBACK(yon_on_popover_closed),NULL);

}