#include <gtk/gtk.h>
#include <glib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "mmyth_ui.h"
#include "mmyth_recordui.h"

/*
 * GMyth library includes 
 */
#include <gmyth/gmyth_scheduler.h>
#include <gmyth/gmyth_util.h>

enum {
    START_DATE_COLUMN = 0,
    TITLE_COLUMN,
    CHAN_ID_COLUMN,
    END_TIME_COLUMN,
    RECORD_ID_COLUMN,
    BASENAME_COLUMN,
    N_COLUMNS
};

gboolean
mmyth_recordui_reload_all(MMythRecordUI * recordui)
{
    gboolean        res = FALSE;

    res = mmyth_recordui_reload_schedule(recordui);

    res = res & mmyth_recordui_reload_record(recordui);


    if (!res)
        g_warning
            ("[%s] Error while reloading schedule and recording content",
             __FUNCTION__);

    return res;
}

gboolean
mmyth_recordui_reload_schedule(MMythRecordUI * recordui)
{
    gint            new_row = 0;
    ScheduleInfo   *schedule_info;
    GList          *schedule_list;
    GtkTreeIter     iter;
    gchar          *start_date_time = NULL;
    gchar          *end_date_time = NULL;
    GString        *str_aux = g_string_new("");
    gint            res;

    gtk_tree_store_clear(recordui->sch_tree_store);

    res =
        gmyth_scheduler_get_schedule_list(recordui->scheduler,
                                          &(schedule_list));
    if (res < 0) {
        g_warning
            ("[%s] Retrieved NULL list of scheduled data from database",
             __FUNCTION__);
        return FALSE;
    }

    for (; schedule_list; schedule_list = schedule_list->next) {
        schedule_info = (ScheduleInfo *) schedule_list->data;

        gtk_tree_store_insert(recordui->sch_tree_store, &iter, NULL,
                              new_row++);

        start_date_time =
            gmyth_util_time_to_string_from_time_val(schedule_info->
                                                    start_time);
        end_date_time =
            gmyth_util_time_to_string_from_time_val(schedule_info->
                                                    end_time);

        g_string_printf(str_aux, "%d", schedule_info->channel_id);

        gtk_tree_store_set(recordui->sch_tree_store, &iter, START_DATE_COLUMN, start_date_time, TITLE_COLUMN, schedule_info->title->str, CHAN_ID_COLUMN, str_aux->str, END_TIME_COLUMN, end_date_time,  // It 
                                                                                                                                                                                                        // doesn't 
                                                                                                                                                                                                        // appear
                           RECORD_ID_COLUMN, schedule_info->record_id, -1); // the 
                                                                            // last 
                                                                            // line 
                                                                            // is 
                                                                            // a 
                                                                            // hidden 
                                                                            // item 
                                                                            // to 
                                                                            // be 
                                                                            // used 
                                                                            // in 
                                                                            // searching 
                                                                            // tasks
    }

    g_debug("[%s] %d lines added to schedule list UI", __FUNCTION__,
            new_row);

    /*
     * free allocated memory 
     */
    if (!start_date_time)
        g_free(start_date_time);
    if (!end_date_time)
        g_free(end_date_time);
    g_string_free(str_aux, FALSE);

    return TRUE;
}

gboolean
mmyth_recordui_reload_record(MMythRecordUI * recordui)
{
    gint            new_row = 0;
    RecordedInfo   *recorded_info;
    GList          *record_list = NULL;
    GtkTreeIter     iter;
    gchar          *start_date_time = NULL;
    gchar          *end_date_time = NULL;
    GString        *str_aux = g_string_new("");
    gint            res;

    gtk_tree_store_clear(recordui->rec_tree_store);

    res =
        gmyth_scheduler_get_recorded_list(recordui->scheduler,
                                          &record_list);
    if (res < 0) {
        g_warning
            ("[%s] Retrieved NULL list of recorded data from database",
             __FUNCTION__);
        return FALSE;
    }

    for (; record_list; record_list = record_list->next) {
        recorded_info = (RecordedInfo *) record_list->data;

        gtk_tree_store_insert(recordui->rec_tree_store, &iter, NULL,
                              new_row++);

        start_date_time =
            gmyth_util_time_to_string_from_time_val(recorded_info->
                                                    start_time);
        end_date_time =
            gmyth_util_time_to_string_from_time_val(recorded_info->
                                                    end_time);

        g_string_printf(str_aux, "%d", recorded_info->channel_id);

        gtk_tree_store_set(recordui->rec_tree_store, &iter, START_DATE_COLUMN, start_date_time, TITLE_COLUMN, recorded_info->title->str, CHAN_ID_COLUMN, str_aux->str, END_TIME_COLUMN, end_date_time,  // It 
                                                                                                                                                                                                        // doesn't 
                                                                                                                                                                                                        // appear
                           RECORD_ID_COLUMN, recorded_info->record_id,
                           BASENAME_COLUMN, recorded_info->basename->str,
                           -1);
        // the last line is a hidden item to be used in searching tasks 
    }

    g_debug("[%s] %d lines added to record list UI", __FUNCTION__,
            new_row);

    /*
     * free allocated memory 
     */
    if (NULL != start_date_time)
        g_free(start_date_time);
    if (NULL != end_date_time)
        g_free(end_date_time);
    g_string_free(str_aux, FALSE);

    return TRUE;
}


MMythRecordUI  *
mmyth_recordui_new(GMythBackendInfo * backend_info)
{
    MMythRecordUI  *recordui = g_new0(MMythRecordUI, 1);

    g_return_val_if_fail(backend_info != NULL, NULL);

    recordui->backend_info = backend_info;

    recordui->scrolled_window = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW
                                   (recordui->scrolled_window),
                                   GTK_POLICY_AUTOMATIC,
                                   GTK_POLICY_AUTOMATIC);

    recordui->viewport = gtk_viewport_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(recordui->scrolled_window),
                      recordui->viewport);

    recordui->notebook = gtk_notebook_new();
    gtk_container_set_border_width(GTK_CONTAINER(recordui->notebook), 1);
    gtk_notebook_set_scrollable(GTK_NOTEBOOK(recordui->notebook), TRUE);
    gtk_notebook_popup_enable(GTK_NOTEBOOK(recordui->notebook));
    gtk_container_add(GTK_CONTAINER(recordui->viewport),
                      recordui->notebook);
    gtk_notebook_popup_disable(GTK_NOTEBOOK(recordui->notebook));

    /*
     * Schedule tab 
     */
    recordui->sch_scrolled_window = gtk_scrolled_window_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(recordui->notebook),
                      recordui->sch_scrolled_window);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW
                                   (recordui->sch_scrolled_window),
                                   GTK_POLICY_AUTOMATIC,
                                   GTK_POLICY_AUTOMATIC);
    gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW
                                        (recordui->sch_scrolled_window),
                                        GTK_SHADOW_IN);

    /*
     * The basename column in the sched_tree_store is not being used
     */
    recordui->sch_tree_store =
        gtk_tree_store_new(N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING,
                           G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT,
                           G_TYPE_STRING);

    recordui->sch_treeview =
        gtk_tree_view_new_with_model(GTK_TREE_MODEL
                                     (recordui->sch_tree_store));
    gtk_container_add(GTK_CONTAINER(recordui->sch_scrolled_window),
                      recordui->sch_treeview);
    recordui->sch_renderer = gtk_cell_renderer_text_new();
    // g_object_set(G_OBJECT(renderer1), "foreground", "green",
    // "background", "black", NULL);
    recordui->sch_column1 =
        gtk_tree_view_column_new_with_attributes("Start time",
                                                 recordui->sch_renderer,
                                                 "text", START_DATE_COLUMN,
                                                 NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->sch_treeview),
                                recordui->sch_column1);
    recordui->sch_column2 =
        gtk_tree_view_column_new_with_attributes("Title",
                                                 recordui->sch_renderer,
                                                 "text", TITLE_COLUMN,
                                                 NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->sch_treeview),
                                recordui->sch_column2);
    recordui->sch_column3 =
        gtk_tree_view_column_new_with_attributes("Channel",
                                                 recordui->sch_renderer,
                                                 "text", CHAN_ID_COLUMN,
                                                 NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->sch_treeview),
                                recordui->sch_column3);
    gtk_tree_view_column_set_resizable(recordui->sch_column1, TRUE);
    gtk_tree_view_column_set_resizable(recordui->sch_column2, TRUE);
    gtk_tree_view_column_set_resizable(recordui->sch_column3, TRUE);
    gtk_tree_view_column_set_reorderable(recordui->sch_column1, TRUE);
    gtk_tree_view_column_set_reorderable(recordui->sch_column2, TRUE);
    gtk_tree_view_column_set_reorderable(recordui->sch_column3, TRUE);
    // recordui->sch_column4 = 
    // gtk_tree_view_column_new_with_attributes("",
    // recordui->sch_renderer, "text", END_TIME_COLUMN, NULL);
    // gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->sch_treeview), 
    // recordui->sch_column4);

    recordui->sch_label = gtk_label_new(("Schedule"));
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(recordui->notebook),
                               gtk_notebook_get_nth_page(GTK_NOTEBOOK
                                                         (recordui->
                                                          notebook), 0),
                               recordui->sch_label);

    // Record items tab
    // g_object_set(G_OBJECT(renderer2), "foreground", "blue", NULL);
    recordui->rec_scrolled_window = gtk_scrolled_window_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(recordui->notebook),
                      recordui->rec_scrolled_window);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW
                                   (recordui->rec_scrolled_window),
                                   GTK_POLICY_AUTOMATIC,
                                   GTK_POLICY_AUTOMATIC);
    gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW
                                        (recordui->rec_scrolled_window),
                                        GTK_SHADOW_IN);

    recordui->rec_tree_store =
        gtk_tree_store_new(N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING,
                           G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT,
                           G_TYPE_STRING);
    recordui->rec_treeview =
        gtk_tree_view_new_with_model(GTK_TREE_MODEL
                                     (recordui->rec_tree_store));
    gtk_container_add(GTK_CONTAINER(recordui->rec_scrolled_window),
                      recordui->rec_treeview);
    recordui->rec_renderer = gtk_cell_renderer_text_new();
    // g_object_set(G_OBJECT(renderer1), "foreground", "green",
    // "background", "black", NULL);

    recordui->rec_column1 =
        gtk_tree_view_column_new_with_attributes("Start time",
                                                 recordui->rec_renderer,
                                                 "text", START_DATE_COLUMN,
                                                 NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->rec_treeview),
                                recordui->rec_column1);
    recordui->rec_column2 =
        gtk_tree_view_column_new_with_attributes("Title",
                                                 recordui->rec_renderer,
                                                 "text", TITLE_COLUMN,
                                                 NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->rec_treeview),
                                recordui->rec_column2);
    recordui->rec_column3 =
        gtk_tree_view_column_new_with_attributes("Channel",
                                                 recordui->rec_renderer,
                                                 "text", CHAN_ID_COLUMN,
                                                 NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->rec_treeview),
                                recordui->rec_column3);
    gtk_tree_view_column_set_resizable(recordui->rec_column1, TRUE);
    gtk_tree_view_column_set_resizable(recordui->rec_column2, TRUE);
    gtk_tree_view_column_set_resizable(recordui->rec_column3, TRUE);
    gtk_tree_view_column_set_reorderable(recordui->rec_column1, TRUE);
    gtk_tree_view_column_set_reorderable(recordui->rec_column2, TRUE);
    gtk_tree_view_column_set_reorderable(recordui->rec_column3, TRUE);
    // recordui->rec_column4 =
    // gtk_tree_view_column_new_with_attributes("",
    // recordui->rec_renderer, "text", END_TIME_COLUMN, NULL);
    // gtk_tree_view_append_column(GTK_TREE_VIEW(recordui->rec_treeview),
    // recordui->rec_column4);

    recordui->rec_label = gtk_label_new(("Recorded"));
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(recordui->notebook),
                               gtk_notebook_get_nth_page(GTK_NOTEBOOK
                                                         (recordui->
                                                          notebook), 1),
                               recordui->rec_label);

    // Gets the mmyth scheduler manager
    recordui->scheduler = gmyth_scheduler_new(backend_info);

    /*
     * init connection to the backend 
     */
    gmyth_scheduler_connect(recordui->scheduler,
                            recordui->scheduler->backend_info);

    return recordui;
}

void
mmyth_recordui_free(MMythRecordUI * recordui)
{
    // FIXME: Release memory here!
    /*
     * close connection to the backend 
     */
    gmyth_scheduler_disconnect(recordui->scheduler);
}

void
mmyth_recordui_delete_selected(GtkButton * button,
                               MMythRecordUI * recordui)
{
    GtkTreeSelection *selection;
    GtkTreeModel   *list_store;
    GtkTreeIter     iter;
    int             index;
    int             curr_page = 0;

    curr_page =
        gtk_notebook_get_current_page(GTK_NOTEBOOK(recordui->notebook));

    if (curr_page == 0) {
        selection =
            gtk_tree_view_get_selection(GTK_TREE_VIEW
                                        (recordui->sch_treeview));
        if (selection != NULL) {
            gtk_tree_selection_get_selected(selection, &list_store, &iter);
            gtk_tree_model_get(list_store, &iter, RECORD_ID_COLUMN, &index,
                               -1);
            gmyth_scheduler_delete_schedule(recordui->scheduler, index);
            mmyth_recordui_reload_schedule(recordui);
            return;
        }

    } else if (curr_page == 1) {
        selection =
            gtk_tree_view_get_selection(GTK_TREE_VIEW
                                        (recordui->rec_treeview));
        if (selection != NULL) {
            gtk_tree_selection_get_selected(selection, &list_store, &iter);
            gtk_tree_model_get(list_store, &iter, RECORD_ID_COLUMN, &index,
                               -1);
            gmyth_scheduler_delete_recorded(recordui->scheduler, index);
            mmyth_recordui_reload_record(recordui);
            return;
        }
    }

    g_warning("[%s] None element was removed from the list", __FUNCTION__);
}

/*
 * FIXME: change this function name, it is returning the basename_column
 * that represents the nuv filename of the recorded content 
 */
gchar          *
mmyth_recordui_get_selected_recorded(MMythRecordUI * recordui)
{
    GtkTreeSelection *selection = NULL;
    GtkTreeModel   *list_store = NULL;
    GtkTreeIter     iter;
    gchar          *path = NULL;

    /*
     * returning nuv filename, basename_column 
     */
    selection =
        gtk_tree_view_get_selection(GTK_TREE_VIEW(recordui->rec_treeview));
    if (gtk_tree_selection_get_selected(selection, &list_store, &iter)) {
        gtk_tree_model_get(list_store, &iter, BASENAME_COLUMN, &path, -1);
    }
    // FIXME: MOVE THIS TO OTHER PLACE
    return path;
}