/* ====================================================================
 * FTD4Linux Software License, Version 1.0
 *
 * Copyright (c) 2000-2004 The FTD4Linux Development Team.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        FTD4Linux Development Team (http://www.ftd4linux.2y.net/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "FTD" and "FTD4Linux" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact alguno@ftd4linux.2y.net.
 *
 * 5. Products derived from this software may not be called "FTD4Linux",
 *    nor may "FTD4Linux" appear in their name, without prior written
 *    permission of the FTD4Linux Development Team.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE FTD4LINUX DEVELOPMENT TEAM OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "ftd_gui_main.h"
#include "ftd_gui_worksheet.h"
#include "ftd_gui_center.h"
#include "ftd_gui_center_eventlist.h"
#include "ftd_gui_errhandler.h"
#include "ftd_gui_pixbuf.h"
#include "ftd_gui_xslt.h"
#include "ftd_gui_browser.h"
#include "ftd_gui_parse.h"

void ftd_gui_center_eventlist_row_activated(GtkTreeView *treeview, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data);

void
ftd_gui_center_eventlist_new(void)
{
    GtkWidget *label;
    FtdGuiCenterEventList *eventlist = (FtdGuiCenterEventList *) g_malloc0(sizeof(FtdGuiCenterEventList));
    g_assert(gui);
    g_assert(gui->worksheet);
    gui->worksheet->center->eventlist = eventlist;

    eventlist->browser_data = ftd_gui_browser_new(gui->worksheet->center->widget, FALSE);
    eventlist->widget = ftd_gui_browser_get_widget(eventlist->browser_data);

    label = gtk_label_new ("Postoverzicht");
    gtk_widget_show (label);
    gtk_notebook_set_tab_label (GTK_NOTEBOOK (gui->worksheet->center->widget),
                                gtk_notebook_get_nth_page (
                                    GTK_NOTEBOOK (gui->worksheet->center->widget), -1), label);
    gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);

    /* Signal handler om het statusvenstertje te vernietigen wanneer
     * het laden van de HTML pagina klaar is */
    ftd_gui_browser_set_load_finished_cb(eventlist->browser_data, ftd_gui_center_eventlist_load_finished, NULL);

    /* Signal handler om de url klikjes vanuit het componentje op te vangen */
    ftd_gui_browser_set_link_clicked_cb(eventlist->browser_data, ftd_gui_center_eventlist_open_uri, NULL);

    gtk_notebook_set_current_page (GTK_NOTEBOOK (gui->worksheet->center->widget), -1);
}

gboolean
ftd_gui_center_eventlist_show(gpointer data)
{
    int pagenum;

    pagenum = gtk_notebook_page_num(GTK_NOTEBOOK(gui->worksheet->center->widget), gui->worksheet->center->eventlist->widget);
    gtk_notebook_set_current_page(GTK_NOTEBOOK(gui->worksheet->center->widget), pagenum);

    ftd_gui_browser_navigate(gui->worksheet->center->eventlist->browser_data, HTML_LIST_FILE);

    return FALSE;
}

void
ftd_gui_center_eventlist_load_finished (GtkWidget *caller, gpointer data)
{
    g_assert (gui);

    ftd_gui_status_push();

    gtk_statusbar_push(GTK_STATUSBAR(gui->statusbar), 0, "Klaar...");
}

static void
forum_fetch_cb(FtdErrorCode retval, int posting, time_t lastCheck, char *errmsg, gpointer data)
{
    FtdGuiCenterEventInfo *eventinfo = (FtdGuiCenterEventInfo *) data;

    if (retval != ERROR_NONE) {
        ftd_gui_errhandler(gui->window, FTD_ONDERDEEL_EVENTINFO_FORUM, retval, errmsg);
        ftd_gui_center_eventinfo_sluiten(eventinfo->cmdclose, NULL);
        return;
    }

    // Is het tabblad nog wel aanwezig?
    if (eventinfo->can_be_destroyed) {
        // Neen, geef eventinfo vrij en kap er maar gelijk mee
        FTDEventlist *eventlist = ftd_eventlist_get();
        ftd_eventlist_set_posting_is_active(eventlist, eventinfo->post_id, FALSE);
        g_object_unref(eventlist);

        g_free(eventinfo);
        return;
    }

    retval = ftd_gui_center_eventinfo_process(posting);
    if (retval != ERROR_NONE) {
        ftd_gui_errhandler(gui->window, FTD_ONDERDEEL_EVENTINFO_FORUM, retval, NULL);
        ftd_gui_center_eventinfo_sluiten(eventinfo->cmdclose, NULL);
        return;
    }

    // Toon de gegevens op het scherm
    ftd_gui_center_eventinfo_show(eventinfo->widget, NULL);

    eventinfo->still_in_use = FALSE;
}

static void
open_posting_fase2(FtdErrorCode retval, int posting, char *errmsg, gpointer data)
{
    FtdGuiCenterEventInfo *eventinfo = (FtdGuiCenterEventInfo *) data;
    FtdEvent *event;
    FTDEventlist *eventlist;

    if (retval != ERROR_NONE) {
        ftd_gui_errhandler(gui->window, FTD_ONDERDEEL_EVENTINFO, retval, errmsg);
        ftd_gui_center_eventinfo_sluiten(eventinfo->cmdclose, NULL);
        return;
    }

    // Is het tabblad nog wel aanwezig?
    if (eventinfo->can_be_destroyed) {
        // Neen, geef eventinfo vrij en kap er maar gelijk mee
        FTDEventlist *eventlist = ftd_eventlist_get();
        ftd_eventlist_set_posting_is_active(eventlist, eventinfo->post_id, FALSE);
        g_object_unref(eventlist);

        g_free(eventinfo);
        return;
    }

    // Stel de titel van het tabblad goed in
    eventlist = ftd_eventlist_get();
    event = ftd_eventlist_lookup_id(eventlist, posting);
    g_object_unref(eventlist);

    if (event && event->title) {
        char bericht[64];
        FtdString *tmp;

        tmp = ftd_string_replace(event->title, "&amp;", "&");
        if (ftd_string_length(tmp) > 20) {
            char title[21];
            strncpy(title, ftd_string_value(tmp), 21); // Dit levert onder Win32 een truncate melding op, maar dat is ook de bedoeling in deze situatie
            title[20] = '\0';
            snprintf(bericht, sizeof(bericht), "%s...", title);
        } else {
            snprintf(bericht, sizeof(bericht), "%s", ftd_string_value(tmp));
        }

        ftd_event_free(event);
        event = NULL;

        gtk_label_set_text(GTK_LABEL(eventinfo->label), bericht);
    }

    // Haal alle bijbehorende forum reacties op
    ftd_events_forum_fetch_async(posting, (time_t) 0, forum_fetch_cb, data);
}

static void
open_posting(int posting)
{
    FtdErrorCode retval;
    char *errmsg;
    FtdGuiCenterEventInfo *eventinfo;

    // Open een tabblad voor de postinfo in te dumpen
    eventinfo = ftd_gui_center_eventinfo_new(posting);

    if (!eventinfo) {
        return;
    }

    eventinfo->still_in_use = TRUE;

    /* Haal de gegevens van het FTD event op. */
    ftd_eventinfo_fetch_async(posting, open_posting_fase2, eventinfo);
}

static void
refresh_posting(int posting)
{
    int teller;
    int current_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(gui->worksheet->center->widget));

    for (teller = 0; teller < MAX_EVENT_INFO; teller++) {
        FtdGuiCenterEventInfo *eventinfo = gui->worksheet->center->eventinfo[teller];
        if (eventinfo) {
            int page = gtk_notebook_page_num(GTK_NOTEBOOK(gui->worksheet->center->widget), eventinfo->widget);
            if (page == current_page) {
                FtdErrorCode retval;
                char *errmsg;

                eventinfo->still_in_use = TRUE;

                /* Haal de gegevens van het FTD event op. */
                ftd_eventinfo_fetch_async(posting, open_posting_fase2, eventinfo);
            }
        }
    }
}

gboolean
ftd_gui_center_eventlist_open_uri (GtkWidget *embed, const char *uri, gpointer data)
{
    char *begin;

    g_assert (gui);

    /* =======================
     * Externe URL's (#link)
     * =======================
     */
    begin = strstr(uri, "#link");
    if (begin) {
        begin += 5;

        ftd_gui_center_launch_browser(begin);

        return TRUE;
    }

    /* =======================
     * #post
     * =======================
     */
    begin = strstr(uri, "#post");
    if (begin) {
        begin += 5;

        if (GPOINTER_TO_INT(data) == 1) {
            // Refresh de inhoud van de postinfo
            refresh_posting(atoi(begin));
        } else {
            open_posting(atoi(begin));
        }

        return TRUE;
    }

    /* ========================
     * #sortmode
     * ========================
     */
    begin = strstr(uri, "#sortmode");
    if (begin) {
         /* Laad gegevens uit de posts cache, sorteer deze en bewaar het als HTML_LIST_FILE */
        int sortmode;
        int ret;
        FtdFilter *filter;
        FTDEventlist *eventlist;
        char *xslt_path;
        FtdString *uitvoer;

        eventlist = ftd_eventlist_get();
        filter = ftd_eventlist_get_filter(eventlist);

        begin += 9;
        sortmode = atoi(begin);

        switch (sortmode) {
            case 0:
                if (filter->veld == FTDEVENT_SORT_DATUM) {
                    filter->asc = !filter->asc;
                } else {
                    filter->asc = FALSE;   // Sorteer standaard met meest recente item eerst
                }

                filter->veld = FTDEVENT_SORT_DATUM;

                break;
            case 1:
                if (filter->veld == FTDEVENT_SORT_TITEL) {
                    filter->asc = !filter->asc;
                } else {
                    filter->asc = TRUE;
                }

                filter->veld = FTDEVENT_SORT_TITEL;

                break;
            case 2:
                if (filter->veld == FTDEVENT_SORT_POSTER) {
                    filter->asc = !filter->asc;
                } else {
                    filter->asc = TRUE;
                }

                filter->veld = FTDEVENT_SORT_POSTER;

                break;
            case 5:
                if (filter->veld == FTDEVENT_SORT_RATING) {
                    filter->asc = !filter->asc;
                } else {
                    filter->asc = TRUE;
                }

                filter->veld = FTDEVENT_SORT_RATING;

                break;
            default:
                g_warning("ftd_gui_center_eventlist_open_uri(): Onbekende sortmode :%i\n", sortmode);
                break;
        }

        ftd_eventlist_apply_filter(eventlist, filter);
        g_object_unref(eventlist);

        uitvoer = ftd_events_sort_filtered(ftd_gui_parse);

        if (filter->categoriseerd) {
            xslt_path = XSLT_TYPE_LIST;
        } else {
            xslt_path = XSLT_TYPE_LIST_TOTAL;
        }

        ret = ftd_gui_xslt_process (uitvoer, xslt_path, HTML_LIST_FILE);

        g_free(xslt_path);
        ftd_filter_free_filter(filter);

        ftd_string_free (uitvoer);

        if (ret != 0) {
            g_warning("ftd_gui_center_eventlist_open_uri(): verwerken van xslt sheet mislukt\n");
            return TRUE;
        }

        ftd_gui_center_eventlist_show(NULL);

        return TRUE;
    }

    /* =======================
     * #info
    * =======================
    */
    begin = strstr(uri, "#info");
    if (begin) {
        begin += 5;

        ftd_gui_profile_show(begin);

        return TRUE;
    }

    /* =======================
     * #add
     * =======================
    */
    begin = strstr(uri, "#add");
    if (begin) {
        int postid;
        begin += 4;
        postid = atoi(begin);

        if (ftd_watchlist_is_in_list(postid)) {
            int teller;
            char * path_tmp = NULL;
            FtdString * path_tmp2 = NULL;
            FtdString * path_tmp3 = NULL;
            FtdString * path_tmp4 = NULL;
            char * path = NULL;
            char buf[2048];
            char buf2[2048];

            // Postid is reeds aanwezig in de watchlist -> verwijderen
            ftd_watchlist_remove(postid);

            // Pas het watchlist icoontje in het postoverzicht aan
            path_tmp = ftd_file_parse_data_dir(NULL);
            path_tmp2 = ftd_string_new(path_tmp);
            path_tmp3 = ftd_string_replace(path_tmp2, " ", "%20");
            path_tmp4 = ftd_string_replace(path_tmp3, "\\", "/");
            path = ftd_string_value(path_tmp4);
            snprintf(buf, sizeof(buf), "file://%s/images/dlb1a.bmp", path);
            ftd_string_free(path_tmp4);
            ftd_string_free(path_tmp3);
            ftd_string_free(path_tmp2);
            g_free(path_tmp);

            snprintf(buf2, sizeof(buf2), "p%d", postid);
            ftd_gui_browser_set_element_attribute(gui->worksheet->center->eventlist->browser_data, buf2, "src", buf);


            // Pas het watchlist icoontje in een eventueel geopende postinfo aan
            path_tmp = ftd_file_parse_data_dir(NULL);
            path_tmp2 = ftd_string_new(path_tmp);
            path_tmp3 = ftd_string_replace(path_tmp2, " ", "%20");
            path_tmp4 = ftd_string_replace(path_tmp3, "\\", "/");
            path = ftd_string_value(path_tmp4);
            snprintf(buf, sizeof(buf), "file://%s/images/b4-1.bmp", path);
            ftd_string_free(path_tmp4);
            ftd_string_free(path_tmp3);
            ftd_string_free(path_tmp2);
            g_free(path_tmp);

            if( gui->worksheet->center->eventinfo ) {
                for( teller = 0; teller < MAX_EVENT_INFO; teller++ ) {
                    if( gui->worksheet->center->eventinfo[teller] && gui->worksheet->center->eventinfo[teller]->post_id == postid ) {
                        ftd_gui_browser_set_element_attribute( gui->worksheet->center->eventinfo[teller]->browser_data, "dlbut", "src", buf );
                        break;
                    }
                }
            }
        } else {
            int teller;
            char * path_tmp = NULL;
            FtdString * path_tmp2 = NULL;
            FtdString * path_tmp3 = NULL;
            FtdString * path_tmp4 = NULL;
            char * path = NULL;
            char buf[2048];
            char buf2[2048];

            ftd_watchlist_add(postid);

            // Pas het watchlist icoontje in het postoverzicht aan
            path_tmp = ftd_file_parse_data_dir(NULL);
            path_tmp2 = ftd_string_new(path_tmp);
            path_tmp3 = ftd_string_replace(path_tmp2, " ", "%20");
            path_tmp4 = ftd_string_replace(path_tmp3, "\\", "/");
            path = ftd_string_value(path_tmp4);
            snprintf(buf, sizeof(buf), "file://%s/images/dlb2a.bmp", path);
            ftd_string_free(path_tmp4);
            ftd_string_free(path_tmp3);
            ftd_string_free(path_tmp2);
            g_free(path_tmp);

            snprintf(buf2, sizeof(buf2), "p%d", postid);
            ftd_gui_browser_set_element_attribute(gui->worksheet->center->eventlist->browser_data, buf2, "src", buf);

            // Pas het watchlist icoontje in een eventueel geopende postinfo aan
            path_tmp = ftd_file_parse_data_dir(NULL);
            path_tmp2 = ftd_string_new(path_tmp);
            path_tmp3 = ftd_string_replace(path_tmp2, " ", "%20");
            path_tmp4 = ftd_string_replace(path_tmp3, "\\", "/");
            path = ftd_string_value(path_tmp4);
            snprintf(buf, sizeof(buf), "file://%s/images/b4-3.bmp", path);
            ftd_string_free(path_tmp4);
            ftd_string_free(path_tmp3);
            ftd_string_free(path_tmp2);
            g_free(path_tmp);

            if( gui->worksheet->center->eventinfo ) {
                for( teller = 0; teller < MAX_EVENT_INFO; teller++ ) {
                    if( gui->worksheet->center->eventinfo[teller] && gui->worksheet->center->eventinfo[teller]->post_id == postid ) {
                        ftd_gui_browser_set_element_attribute( gui->worksheet->center->eventinfo[teller]->browser_data, "dlbut", "src", buf );
                        break;
                    }
                }
            }
        }

        return TRUE;
    }

    return FALSE;
}
