/* ====================================================================
 * 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 "ftd_gui_main.h"
#include "ftd_gui_center.h"
#include "ftd_gui_worksheet.h"
#include "ftd_gui_errhandler.h"
#include "ftd_gui_xslt.h"
#include "ftd_gui_browser.h"
#include "ftd_gui_parse.h"

void
ftd_gui_center_watchlist_new(void)
{
    GtkWidget *label;
    GtkWidget *tabby;
    FtdGuiCenterWatchlist *watchlist;
    int teller;

    g_assert(gui);
    g_assert(gui->worksheet);
    g_assert(gui->worksheet->center);

    // Hebben we reeds een watchlist open staan ?
    if (gui->worksheet->center->watchlist) {
        // Zoek de tab waar de watchlist op vermeld staat en activeer deze
        for (teller = 0; teller < gtk_notebook_get_n_pages(GTK_NOTEBOOK (gui->worksheet->center->widget)); teller++) {
            if (gtk_notebook_get_nth_page(GTK_NOTEBOOK (gui->worksheet->center->widget), teller) == gui->worksheet->center->watchlist->widget) {
                // Activeer de tab. De signal handler van de notebook zorgt ervoor
                // dat de gegevens opnieuw aangemaakt en getoond worden.
                gtk_notebook_set_current_page (GTK_NOTEBOOK (gui->worksheet->center->widget), teller);

                return;
            }
        }
    }

    watchlist = (FtdGuiCenterWatchlist *) g_malloc0(sizeof(FtdGuiCenterWatchlist));
    gui->worksheet->center->watchlist = watchlist;

    /* Initialiseer de inhoud van het schermpie */
    watchlist->browser_data = ftd_gui_browser_new(gui->worksheet->center->widget, FALSE);
    watchlist->widget = ftd_gui_browser_get_widget(watchlist->browser_data);

    /* Voeg een pagina toe aan de notebook, met bijbehorend sluit-knopje */
    label = gtk_label_new ("Watchlist");
    gtk_widget_show (label);

    tabby = gtk_hbox_new(FALSE, 2);
    watchlist->cmdclose = gtk_button_new();
    gtk_widget_set_size_request(GTK_WIDGET(watchlist->cmdclose), 16, 16);
    gtk_container_add(GTK_CONTAINER(watchlist->cmdclose), gtk_image_new_from_stock(GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU));
    gtk_widget_show_all (watchlist->cmdclose);
    gtk_button_set_relief(GTK_BUTTON(watchlist->cmdclose), GTK_RELIEF_NONE);

    gtk_box_pack_start(GTK_BOX(tabby), label, TRUE, TRUE, 0);
    gtk_box_pack_start(GTK_BOX(tabby), watchlist->cmdclose, FALSE, FALSE, 0);

    gtk_notebook_set_tab_label (GTK_NOTEBOOK (gui->worksheet->center->widget), watchlist->widget, tabby);

    /* Signal handler voor het afsluiten knopje */
    g_signal_connect (GTK_WIDGET (watchlist->cmdclose), "clicked", G_CALLBACK(ftd_gui_center_watchlist_sluiten), NULL);

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

    ftd_gui_center_watchlist_show(NULL, NULL);

    /* Trek gelijk de aandacht */
    //gtk_widget_grab_focus (GTK_WIDGET (watchlist->widget));
    gtk_notebook_set_current_page (GTK_NOTEBOOK (gui->worksheet->center->widget), -1);
}

void
ftd_gui_center_watchlist_show (GtkWidget *caller, gpointer data)
{
    FtdGuiCenterWatchlist *watchlist;

    g_assert(gui);
    g_assert(gui->worksheet);
    g_assert(gui->worksheet->center);
    g_assert(gui->worksheet->center->watchlist);
    watchlist = gui->worksheet->center->watchlist;

    ftd_gui_browser_navigate(watchlist->browser_data, HTML_WATCHLIST_FILE);
}

void
ftd_gui_center_watchlist_sluiten (GtkWidget *caller, gpointer data)
{
    FtdGuiCenterWatchlist *watchlist;

    g_assert(gui);
    g_assert(gui->worksheet);
    g_assert(gui->worksheet->center);
    g_assert(gui->worksheet->center->watchlist);
    watchlist = gui->worksheet->center->watchlist;

    /* Verwijder de pagina uit de notebook waar het schermpje in geplaatst is */
    ftd_gui_browser_destroy(watchlist->browser_data);

    /* Verwijder deze postinfo uit de gui */
    g_free(watchlist);
    gui->worksheet->center->watchlist = NULL;
}

gboolean
ftd_gui_center_watchlist_open_uri (GtkWidget *embed, const char *uri, gpointer data)
{
    FtdGuiCenterWatchlist *watchlist;
    char *begin;

    g_assert(gui);
    g_assert(gui->worksheet);
    g_assert(gui->worksheet->center);
    g_assert(gui->worksheet->center->watchlist);
    watchlist = gui->worksheet->center->watchlist;

    begin = strstr(uri, "#link");
    if (begin) {
        begin += 5;

        ftd_gui_center_launch_browser(begin);

        return TRUE;
    }

    if (strstr(uri, "#post")) {
        return ftd_gui_center_eventlist_open_uri(NULL, uri, NULL);
    }

    begin = strstr(uri, "#remove");
    if (begin) {
        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];
#ifndef NO_EXTERNAL_BROWSER
        char * elementId = NULL;
#endif
        int posting;

        begin += 7;
        posting = atoi(begin);
        ftd_watchlist_remove(posting);

        // Maak de watchlist opnieuw aan en toon deze
        ftd_gui_center_watchlist_create();

        ftd_gui_center_watchlist_show(NULL, NULL);

        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);
        snprintf(buf2, sizeof(buf2), "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);

        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 == posting ) {
                    ftd_gui_browser_set_element_attribute(gui->worksheet->center->eventinfo[teller]->browser_data, "dlbut", "src", buf );
                    break;
                }
            }
        }

#ifdef NO_EXTERNAL_BROWSER
        if (gui->worksheet->center->eventlist) {
            ftd_gui_center_eventlist_toggle_watchlist (posting);
        }
#else
        elementId = (char *) g_malloc( strlen( begin ) + 2 );
        snprintf( elementId, strlen( begin ) + 2, "p%s", begin );
        if( gui->worksheet->center->eventlist ) {
            ftd_gui_browser_set_element_attribute( gui->worksheet->center->eventlist->browser_data, elementId, "src", buf2 );
        }
        g_free( elementId );
#endif

        return TRUE;
    }

    if (strstr(uri, "#clearwlist")) {
        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];
#ifndef NO_EXTERNAL_BROWSER
        char * elementId = NULL;
#endif

        FtdList * watchlist = ftd_watchlist_get();
        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);
        snprintf(buf2, sizeof(buf2), "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);

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

        while( watchlist ) {
            FtdString * watchlistitem = ftd_list_value( watchlist );

#ifdef NO_EXTERNAL_BROWSER
            if (gui->worksheet->center->eventlist) {
                ftd_gui_center_eventlist_toggle_watchlist (atoi(ftd_string_value(watchlistitem)));
            }
#else
            elementId = (char *) g_malloc( strlen( ftd_string_value( watchlistitem ) ) + 2 );
            snprintf( elementId, strlen( ftd_string_value( watchlistitem ) ) + 2, "p%s", ftd_string_value( watchlistitem ) );
            if( gui->worksheet->center->eventlist ) {
                ftd_gui_browser_set_element_attribute( gui->worksheet->center->eventlist->browser_data, elementId, "src", buf2 );
            }
            g_free( elementId );
#endif

            watchlist = ftd_list_next( watchlist );
        }

        ftd_watchlist_clear();

        ftd_gui_center_watchlist_create();
        ftd_gui_center_watchlist_show(NULL, NULL);

        return TRUE;
    }

    if (strstr(uri, "#savewlist")) {
        FtdErrorCode retval;
        char *errmsg = NULL;

        retval = ftd_watchlist_upload(&errmsg);
        if (retval != ERROR_NONE) {
            ftd_gui_errhandler(gui->window, FTD_ONDERDEEL_UPLOAD_WATCHLIST, retval, errmsg);

            if (errmsg) {
                g_free(errmsg);
            }

            return TRUE;
        }

        if (errmsg) {
            g_free(errmsg);
        }

        ftd_gui_dialog_show(NULL, "Uploaden van watchlist succesvol!", gui->window, TRUE);

        ftd_gui_center_watchlist_create();
        ftd_gui_center_watchlist_show(NULL, NULL);

        return TRUE;
    }

    if (strstr(uri, "#loadwlist")) {
        FtdErrorCode retval;
        char *errmsg = NULL;

        retval = ftd_watchlist_download(&errmsg);
        if (retval != ERROR_NONE) {
            ftd_gui_errhandler(gui->window, FTD_ONDERDEEL_DOWNLOAD_WATCHLIST, retval, errmsg);

            if (errmsg) {
                g_free(errmsg);
            }

            return TRUE;
        }

        if (errmsg) {
            g_free(errmsg);
        }

        ftd_gui_dialog_show(NULL, "Downloaden van watchlist succesvol!", gui->window, TRUE);

        ftd_gui_center_watchlist_create();
        ftd_gui_center_watchlist_show(NULL, NULL);

        return TRUE;
    }

    if (strstr(uri, "#dsortmode")) {
        ftd_gui_dialog_show(NULL, "Not yet implemented", gui->window, FALSE);

        return TRUE;
    }

    if (strstr(uri, "#ftdmail")) {
        char *user = strstr(uri, "#ftdmail") + 8;
        ftd_gui_message_new(user, "", NULL, 0, NULL);
        return TRUE;
    }

    if (strstr(uri, "#nzb")) {
        int post_id = atoi(strstr(uri, "#nzb") + 4);
        ftd_gui_nzb_popup(post_id);
    }

    return FALSE;
}

/**
 * Geeft een nette HTML-uitvoer van de watchlist.
 *
 * @return  Een fout-code die aangeeft of dit succesvol was.
 */
FtdErrorCode
ftd_gui_center_watchlist_create(void)
{
    FtdString *uitvoer = ftd_string_new("");
    FtdList *list;
    int retval;
    int teller = 0;
    char *xslt_path;

    uitvoer = ftd_string_append(uitvoer, "<Watchlist>\n");

    list = ftd_config_get()->watchlist;
    while (list) {
        int nummer;
        FtdString *tmp;
        FtdEvent *event;
        FTDEventlist *eventlist;
        FtdString *watchlist = ftd_list_value(list);
        g_assert(watchlist);

        nummer = atoi(ftd_string_value(watchlist));

        // Zoek het bijbehorende event op
        eventlist = ftd_eventlist_get();
        event = ftd_eventlist_lookup_id(eventlist, nummer);
        g_object_unref(eventlist);
        if (event == NULL) {
            // event is niet bekend bij ons, zoek deze op op de FTD server
            char *errmsg = NULL;
            FtdErrorCode retval = ftd_eventinfo_fetch(nummer, &errmsg);
            if (retval != ERROR_NONE) {
                if (errmsg) {
                    g_warning("ftd_gui_center_watchlist_create(): Kan FTD event behorende bij FTD nummer %i niet vinden:\n%s\nPosting zal automatisch uit watchlist verwijderd worden.", nummer, errmsg);
                    g_free(errmsg);
                } else {
                    g_warning("ftd_gui_center_watchlist_create(): Kan FTD event behorende bij FTD nummer %i niet vinden:\nPosting zal automatisch uit watchlist verwijderd worden.", nummer);
                }
                list = ftd_list_next(list);

                ftd_watchlist_remove(nummer);

                continue;
            }

            eventlist = ftd_eventlist_get();
            event = ftd_eventlist_lookup_id(eventlist, nummer);
            g_object_unref(eventlist);
        }

        tmp = ftd_events_sort_print(event, FALSE, teller, ftd_gui_parse);
        teller++;
        uitvoer = ftd_string_append(uitvoer, ftd_string_value(tmp));
        ftd_string_free(tmp);
        list = ftd_list_next(list);

        ftd_event_free(event);
    }

    uitvoer = ftd_string_append(uitvoer, "</Watchlist>\n");
    xslt_path = XSLT_TYPE_WATCHLIST;

    retval = ftd_gui_xslt_process (uitvoer, xslt_path, HTML_WATCHLIST_FILE);

    g_free(xslt_path);
    ftd_string_free(uitvoer);

    return retval;
}

