/* ====================================================================
 * 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_mail.h"
#include "ftd_gui_pixbuf.h"
#include "ftd_gui_message.h"
#include "ftd_gui_errhandler.h"
#include "ftd_gui_xslt.h"
#include "ftd_gui_center_eventlist.h"
#include "ftd_gui_toolbar.h"
#include "ftd_gui_parse.h"

gboolean    ftd_gui_mail_delete_event(GtkWidget *, gpointer);
gboolean    ftd_gui_mail_destroy(GtkWidget *, gpointer);
void        ftd_gui_mail_auto_check_callback(gpointer);
gboolean    ftd_gui_mail_new_mail_blink(gpointer);
static void ftd_gui_mail_row_activated(GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data);

void
ftd_gui_mail_new(void)
{
    FtdGuiMail *mail = (FtdGuiMail *) g_malloc0(sizeof(FtdGuiMail));
    GtkWidget *vbox1;
    GtkWidget *toolbar1;
    GtkWidget *vpaned1;
    GtkWidget *scrolledwindow1;
    GtkWidget *label2;
    GtkWidget *scrolledwindow2;
    GtkWidget *label3;
    GtkCellRenderer *cellRenderer;
    GtkTreeViewColumn *column;
    GtkTreeSelection *select;
    GdkPixbuf *pixbuf;
    GtkWidget *image;
    GtkWidget *label;
    GtkWidget *vbox;
    char *volledigeFilename;
    char *tmp;
    gsize len;
    FtdString *inhoud;
    FtdString *inhoud2;
    char *data_dir;

    g_assert(gui);
    gui->mail = mail;
    gui->mail->selection = NULL;

    mail->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW (mail->window), "FTD Mail");
    gtk_window_set_position (GTK_WINDOW (mail->window), GTK_WIN_POS_CENTER_ALWAYS);
    gtk_window_set_modal (GTK_WINDOW(mail->window), TRUE);
    gtk_widget_set_size_request (mail->window, 600, 400);
    gtk_window_set_transient_for(GTK_WINDOW(mail->window), GTK_WINDOW(gui->window));

    vbox1 = gtk_vbox_new (FALSE, 0);
    gtk_widget_show (vbox1);
    gtk_container_add (GTK_CONTAINER (mail->window), vbox1);

    toolbar1 = gtk_toolbar_new ();
    gtk_widget_show (toolbar1);
    gtk_box_pack_start (GTK_BOX (vbox1), toolbar1, FALSE, FALSE, 0);
    gtk_toolbar_set_style (GTK_TOOLBAR (toolbar1), GTK_TOOLBAR_BOTH);

    pixbuf = ftd_gui_main_get_pixbuf("icon-mail-controleer");
    image = gtk_image_new_from_pixbuf(pixbuf);
    label = gtk_label_new("Controleer");
    vbox = gtk_vbox_new(FALSE, 0);
    mail->cmdControleer = gtk_button_new();
    gtk_button_set_relief(GTK_BUTTON(mail->cmdControleer), GTK_RELIEF_NONE);
    gtk_box_pack_start(GTK_BOX(vbox), image, TRUE, TRUE, 0);
    gtk_box_pack_end(GTK_BOX(vbox), label, FALSE, FALSE, 0);
    gtk_container_add(GTK_CONTAINER(mail->cmdControleer), vbox);
    gtk_container_add(GTK_CONTAINER(toolbar1), mail->cmdControleer);
    gtk_widget_set_size_request(mail->cmdControleer, 100, -1);
    gtk_widget_show_all(mail->cmdControleer);

    pixbuf = ftd_gui_main_get_pixbuf("icon-mail-nieuw");
    image = gtk_image_new_from_pixbuf(pixbuf);
    label = gtk_label_new("Nieuw");
    vbox = gtk_vbox_new(FALSE, 0);
    mail->cmdNieuw = gtk_button_new();
    gtk_button_set_relief(GTK_BUTTON(mail->cmdNieuw), GTK_RELIEF_NONE);
    gtk_box_pack_start(GTK_BOX(vbox), image, TRUE, TRUE, 0);
    gtk_box_pack_end(GTK_BOX(vbox), label, FALSE, FALSE, 0);
    gtk_container_add(GTK_CONTAINER(mail->cmdNieuw), vbox);
    gtk_container_add(GTK_CONTAINER(toolbar1), mail->cmdNieuw);
    gtk_widget_set_size_request(mail->cmdNieuw, 100, -1);
    gtk_widget_show_all(mail->cmdNieuw);

    pixbuf = ftd_gui_main_get_pixbuf("icon-mail-reageer");
    image = gtk_image_new_from_pixbuf(pixbuf);
    label = gtk_label_new("Reageer");
    vbox = gtk_vbox_new(FALSE, 0);
    mail->cmdReageer = gtk_button_new();
    gtk_button_set_relief(GTK_BUTTON(mail->cmdReageer), GTK_RELIEF_NONE);
    gtk_box_pack_start(GTK_BOX(vbox), image, TRUE, TRUE, 0);
    gtk_box_pack_end(GTK_BOX(vbox), label, FALSE, FALSE, 0);
    gtk_container_add(GTK_CONTAINER(mail->cmdReageer), vbox);
    gtk_container_add(GTK_CONTAINER(toolbar1), mail->cmdReageer);
    gtk_widget_set_size_request(mail->cmdReageer, 100, -1);
    gtk_widget_show_all(mail->cmdReageer);
    gtk_widget_set_sensitive(mail->cmdReageer, FALSE);

    pixbuf = ftd_gui_main_get_pixbuf("icon-mail-deleten");
    image = gtk_image_new_from_pixbuf(pixbuf);
    label = gtk_label_new("Deleten");
    vbox = gtk_vbox_new(FALSE, 0);
    mail->cmdDeleten = gtk_button_new();
    gtk_button_set_relief(GTK_BUTTON(mail->cmdDeleten), GTK_RELIEF_NONE);
    gtk_box_pack_start(GTK_BOX(vbox), image, TRUE, TRUE, 0);
    gtk_box_pack_end(GTK_BOX(vbox), label, FALSE, FALSE, 0);
    gtk_container_add(GTK_CONTAINER(mail->cmdDeleten), vbox);
    gtk_container_add(GTK_CONTAINER(toolbar1), mail->cmdDeleten);
    gtk_widget_set_size_request(mail->cmdDeleten, 100, -1);
    gtk_widget_show_all(mail->cmdDeleten);
    gtk_widget_set_sensitive(mail->cmdDeleten, FALSE);

    vpaned1 = gtk_vpaned_new ();
    gtk_widget_show (vpaned1);
    gtk_box_pack_start (GTK_BOX (vbox1), vpaned1, TRUE, TRUE, 0);

    mail->notebook = gtk_notebook_new ();
    gtk_widget_show (mail->notebook);
    gtk_paned_pack1 (GTK_PANED (vpaned1), mail->notebook, FALSE, TRUE);

    gtk_paned_set_position (GTK_PANED (vpaned1), 180);

    scrolledwindow1 = gtk_scrolled_window_new (NULL, NULL);
    gtk_widget_show (scrolledwindow1);
    gtk_container_add (GTK_CONTAINER (mail->notebook), scrolledwindow1);
    gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow1),
                                    GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
    gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow1),
                                         GTK_SHADOW_IN);

    label2 = gtk_label_new ("Ontvangen mail");
    gtk_widget_show (label2);
    gtk_notebook_set_tab_label (GTK_NOTEBOOK (mail->notebook), gtk_notebook_get_nth_page (GTK_NOTEBOOK (mail->notebook), 0), label2);

    scrolledwindow2 = gtk_scrolled_window_new (NULL, NULL);
    gtk_widget_show (scrolledwindow2);
    gtk_container_add (GTK_CONTAINER (mail->notebook), scrolledwindow2);
    gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow2),
                                    GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
    gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow2),
                                         GTK_SHADOW_IN);

    label3 = gtk_label_new ("Verstuurde mail");
    gtk_widget_show (label3);
    gtk_notebook_set_tab_label (GTK_NOTEBOOK (mail->notebook), gtk_notebook_get_nth_page (GTK_NOTEBOOK (mail->notebook), 1), label3);

    volledigeFilename = ftd_file_parse_data_dir("/mail.html");
    if (!g_file_get_contents(volledigeFilename, &tmp, &len, NULL)) {
        char *msg = g_strdup_printf("Het openen van '%s' is mislukt. Dit is een teken dat de OpenFTD installatie niet volledig is!", volledigeFilename);
        ftd_gui_dialog_show(NULL, msg, gui->window, TRUE);
        gtk_main_quit();
        return;
    }

    // In de mail.html staat nog een {$imgDir} vermeld. Deze moet
    // vervangen worden door de echte imgDir
#ifdef WIN32
    {
        char *data_dir2;
        data_dir = ftd_file_parse_data_filename("images/");
        data_dir2 = g_strdup_printf("file://%s\\", data_dir);
        inhoud = ftd_string_new(tmp);
        inhoud2 = ftd_string_replace(inhoud, "{$imgDir}/", data_dir2);
        g_free(data_dir2);
    }
#else
    data_dir = ftd_file_parse_data_filename("images");
    inhoud = ftd_string_new(tmp);
    inhoud2 = ftd_string_replace(inhoud, "{$imgDir}", data_dir);
#endif

    ftd_file_save(HTML_MAIL_FILE, inhoud2, FALSE);

///#ifdef NO_EXTERNAL_BROWSER
#if 0
    g_print(__FILE__ ":%i Not yet implemented\n", __LINE__);
#else
    mail->browser_data = ftd_gui_browser_new(vpaned1, TRUE);
    ftd_gui_browser_navigate(mail->browser_data, HTML_MAIL_FILE);
#endif

    ftd_string_free(inhoud);
    ftd_string_free(inhoud2);
    g_free(volledigeFilename);
    g_free(data_dir);
    g_free(tmp);

    mail->statusbar = gtk_statusbar_new ();
    gtk_widget_show (mail->statusbar);
    gtk_box_pack_start (GTK_BOX (vbox1), mail->statusbar, FALSE, FALSE, 0);

    /* Code om de treeview voor Ontvangen mail's aan te maken */
    mail->treestoreOntvangen = gtk_tree_store_new (4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);

    mail->treeOntvangen = gtk_tree_view_new_with_model (GTK_TREE_MODEL (mail->treestoreOntvangen));
    gtk_widget_show (mail->treeOntvangen);
    gtk_container_add (GTK_CONTAINER (scrolledwindow1), mail->treeOntvangen);
    cellRenderer = gtk_cell_renderer_text_new();
    column = gtk_tree_view_column_new_with_attributes ("Onderwerp", cellRenderer, "text", 0, NULL);
    gtk_tree_view_column_set_min_width (column, 360);
    gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (mail->treeOntvangen), column, -1);

    column = gtk_tree_view_column_new_with_attributes ("Afzender", cellRenderer, "text", 1, NULL);
    gtk_tree_view_column_set_min_width (column, 100);
    gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (mail->treeOntvangen), column, -1);

    column = gtk_tree_view_column_new_with_attributes ("Datum ontvangen", cellRenderer, "text", 2, NULL);
    gtk_tree_view_column_set_min_width (column, 100);
    gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (mail->treeOntvangen), column, -1);

    /* Code om de treeview voor Verzonden mail's aan te maken */
    mail->treestoreVerzonden = gtk_tree_store_new (4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);

    mail->treeVerzonden = gtk_tree_view_new_with_model (GTK_TREE_MODEL (mail->treestoreVerzonden));
    gtk_widget_show (mail->treeVerzonden);
    gtk_container_add (GTK_CONTAINER (scrolledwindow2), mail->treeVerzonden);
    cellRenderer = gtk_cell_renderer_text_new();
    column = gtk_tree_view_column_new_with_attributes ("Onderwerp", cellRenderer, "text", 0, NULL);
    gtk_tree_view_column_set_min_width (column, 360);
    gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (mail->treeVerzonden), column, -1);

    column = gtk_tree_view_column_new_with_attributes ("Ontvanger", cellRenderer, "text", 1, NULL);
    gtk_tree_view_column_set_min_width (column, 100);
    gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (mail->treeVerzonden), column, -1);

    column = gtk_tree_view_column_new_with_attributes ("Datum verstuurd", cellRenderer, "text", 2, NULL);
    gtk_tree_view_column_set_min_width (column, 100);
    gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (mail->treeVerzonden), column, -1);

    /* Signal handlers */
    select = gtk_tree_view_get_selection(GTK_TREE_VIEW (mail->treeOntvangen));
    gtk_tree_selection_set_mode (select, GTK_SELECTION_SINGLE);
    g_signal_connect (G_OBJECT (select), "changed",
                      G_CALLBACK (ftd_gui_mail_callback_treeOntvangen_changed), NULL);


    select = gtk_tree_view_get_selection(GTK_TREE_VIEW (mail->treeVerzonden));
    gtk_tree_selection_set_mode (select, GTK_SELECTION_SINGLE);
    g_signal_connect (G_OBJECT (select), "changed",
                      G_CALLBACK (ftd_gui_mail_callback_treeVerzonden_changed), NULL);

    g_signal_connect((gpointer) mail->cmdControleer, "clicked",
                     G_CALLBACK(ftd_gui_mail_callback_controleer_clicked), NULL);

    g_signal_connect((gpointer) mail->cmdNieuw, "clicked",
                     G_CALLBACK(ftd_gui_mail_callback_nieuw_clicked), NULL);

    g_signal_connect((gpointer) mail->cmdReageer, "clicked",
                     G_CALLBACK(ftd_gui_mail_callback_reageer_clicked), NULL);

    g_signal_connect((gpointer) mail->cmdDeleten, "clicked",
                     G_CALLBACK(ftd_gui_mail_callback_deleten_clicked), NULL);

    g_signal_connect(mail->notebook, "switch-page", G_CALLBACK(ftd_gui_mail_switch_page), NULL);

    g_signal_connect((gpointer) mail->window, "destroy",
                     G_CALLBACK(ftd_gui_mail_destroy), NULL);

    g_signal_connect((gpointer) mail->window, "delete-event",
                     G_CALLBACK(ftd_gui_mail_delete_event), NULL);

    g_signal_connect((gpointer) mail->treeOntvangen, "row-activated",
                     G_CALLBACK(ftd_gui_mail_row_activated), NULL);

    ftd_http_curl_set_ftd_mail_callback(ftd_gui_mail_auto_check_callback, NULL);

    ftd_gui_mail_treeOntvangen_update(NULL);
    ftd_gui_mail_treeVerzonden_update(NULL);
}

gboolean
ftd_gui_mail_delete_event(GtkWidget *caller, gpointer data)
{
    return gtk_widget_hide_on_delete(caller);
}

gboolean
ftd_gui_mail_destroy(GtkWidget *caller, gpointer data)
{
///#ifndef NO_EXTERNAL_BROWSER
#if 1
    ftd_gui_browser_destroy(gui->mail->browser_data);
#endif

    g_free(gui->mail);
    gui->mail = NULL;

    return FALSE;
}

gboolean
ftd_gui_mail_callback_treeOntvangen_changed(GtkTreeSelection *selection, gpointer data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;

    g_assert (gui);

    gui->mail->selection = selection;

    if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
        FtdMailBericht *bericht;
        FtdString *berichtData;
///#ifndef NO_EXTERNAL_BROWSER
#if 1
        FtdString *xmlData;
#endif

        gtk_tree_model_get (GTK_TREE_MODEL(model), &iter, 3, &bericht, -1);

///#ifndef NO_EXTERNAL_BROWSER
#if 1
        xmlData = ftd_string_new("<Mail>\n");
        berichtData = ftd_mail_print(bericht, TRUE, ftd_gui_parse);
        xmlData = ftd_string_append(xmlData, ftd_string_value(berichtData));
        ftd_string_free(berichtData);
        ftd_string_append(xmlData, "</Mail>\n");

        ftd_gui_xslt_process(xmlData, XSLT_TYPE_MAIL, HTML_MAIL_FILE);
        ftd_string_free(xmlData);
#endif

        ftd_gui_mail_callback_load_url(NULL);
        gtk_widget_set_sensitive(gui->mail->cmdReageer, TRUE);
        gtk_widget_set_sensitive(gui->mail->cmdDeleten, TRUE);
    } else {
///#ifndef NO_EXTERNAL_BROWSER
#if 1
        ftd_gui_browser_navigate(gui->mail->browser_data, HTML_MAIL_FILE);
#endif

        gtk_widget_set_sensitive(gui->mail->cmdReageer, FALSE);
        gtk_widget_set_sensitive(gui->mail->cmdDeleten, FALSE);
    }

    return FALSE;
}

gboolean
ftd_gui_mail_callback_treeVerzonden_changed(GtkTreeSelection *selection, gpointer data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;

    g_assert (gui);
    g_assert (gui->mail);

    if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
        FtdMailBericht *bericht;
        FtdString *berichtData;
///#ifndef NO_EXTERNAL_BROWSER
#if 1
        FtdString *xmlData;
#endif

        gtk_tree_model_get (GTK_TREE_MODEL(model), &iter, 3, &bericht, -1);

///#ifndef NO_EXTERNAL_BROWSER
#if 1
        xmlData = ftd_string_new("<Mail>\n");
        berichtData = ftd_mail_print(bericht, TRUE, ftd_gui_parse);
        xmlData = ftd_string_append(xmlData, ftd_string_value(berichtData));
        ftd_string_free(berichtData);
        ftd_string_append(xmlData, "</Mail>\n");

        ftd_gui_xslt_process(xmlData, XSLT_TYPE_MAIL, HTML_MAIL_FILE);
        ftd_string_free(xmlData);
#endif

        ftd_gui_mail_callback_load_url(NULL);
        gtk_widget_set_sensitive(gui->mail->cmdDeleten, TRUE);
    } else {
///#ifndef NO_EXTERNAL_BROWSER
#if 1
        ftd_gui_browser_navigate(gui->mail->browser_data, HTML_MAIL_FILE);
#endif

        gtk_widget_set_sensitive(gui->mail->cmdDeleten, FALSE);
    }

    return FALSE;
}

gboolean
ftd_gui_mail_treeOntvangen_update(gpointer data)
{
    GtkTreeStore *treeStore;
    GtkTreeIter treeIter;
    int ret = 0;
    FtdList *list;

    g_assert (gui);
    g_assert (gui->mail);

    treeStore = gui->mail->treestoreOntvangen;
    gtk_tree_store_clear(treeStore);

    list = (FtdList *) ftd_mail_get();

    while (list) {
        char *date;
        FtdMailBericht *bericht = (FtdMailBericht *) ftd_list_value(list);
        if (bericht->type == MAIL_TYPE_ONTVANGEN) {
            date = ftd_string_date(bericht->stamp);
            gtk_tree_store_insert (treeStore, &treeIter, NULL, ret);
            gtk_tree_store_set (treeStore, &treeIter,
                            0, ftd_string_value(bericht->subject),
                            1, ftd_string_value(bericht->from),
                            2, date,
                            3, bericht,
                            -1);
            g_free(date);
        }
        list = ftd_list_next(list);
    }

    return FALSE;
}

gboolean
ftd_gui_mail_treeVerzonden_update(gpointer data)
{
    GtkTreeStore *treeStore;
    GtkTreeIter treeIter;
    FtdList *list;

    int ret = 0;

    g_assert (gui);
    g_assert (gui->mail);

    treeStore = gui->mail->treestoreVerzonden;
    gtk_tree_store_clear(treeStore);

    list = (FtdList *) ftd_mail_get();

    while (list) {
        char *date;
        FtdMailBericht *bericht = (FtdMailBericht *) ftd_list_value(list);
        if (bericht->type == MAIL_TYPE_VERZONDEN) {
            date = ftd_string_date(bericht->stamp);
            gtk_tree_store_insert (treeStore, &treeIter, NULL, ret);
            gtk_tree_store_set (treeStore, &treeIter,
                            0, ftd_string_value(bericht->subject),
                            1, ftd_string_value(bericht->from),
                            2, date,
                            3, bericht,
                            -1);
            g_free(date);
        }
        list = ftd_list_next(list);
    }

    return FALSE;
}

gboolean
ftd_gui_mail_callback_controleer_clicked(GtkWidget *nop, gpointer data)
{
    char *date;
    time_t stamp;
    char tmp[1024];
    FtdErrorCode retval;
    int numNewMail = -1;
    gboolean mailWaiting = FALSE;
    char *errmsg;

    g_assert(gui);
    g_assert(gui->mail);

    gtk_statusbar_push(GTK_STATUSBAR(gui->mail->statusbar), 0, "Bezig met controleren op nieuwe mail . . .");

    /* Achterhaal of er mailtjes wachten op ons */
    retval = ftd_mail_check(&mailWaiting, &errmsg);

    stamp = time(NULL);
    date = ftd_string_date(stamp);

    if (retval == ERROR_NONE && mailWaiting == FALSE) {     // Geen nieuwe FTD mailtjes
        snprintf(tmp, sizeof(tmp), "%s: Ophalen FTD Mail geslaagd - 0 nieuwe berichten; %i berichten totaal", date, ftd_mail_get_num_messages());
        gtk_statusbar_push(GTK_STATUSBAR(gui->mail->statusbar), 0, tmp);
        g_free(date);
        return FALSE;
    }

    if (retval != ERROR_NONE) {
        ftd_gui_errhandler(gui->mail->window, FTD_ONDERDEEL_CHECKMAIL, retval, errmsg);

        snprintf(tmp, sizeof(tmp), "%s: Controleren op nieuwe FTD Mail mislukt!", date);
        gtk_statusbar_push(GTK_STATUSBAR(gui->mail->statusbar), 0, tmp);
        g_free(date);

        return FALSE;
    }

    snprintf(tmp, sizeof(tmp), "%s: Bezig met ophalen van nieuwe FTD Mail", date);
    gtk_statusbar_push(GTK_STATUSBAR(gui->mail->statusbar), 0, tmp);

    g_free(date);

    /* Er zijn wachtende mailtjes op de server
     * haal deze op en sla ze op alvorens ze te tonen */
    retval = ftd_mail_fetch(&numNewMail, &errmsg);

    stamp = time(NULL);
    date = ftd_string_date(stamp);

    if (retval != ERROR_NONE) {
        ftd_gui_errhandler(gui->mail->window, FTD_ONDERDEEL_FETCHMAIL, retval, errmsg);
        snprintf(tmp, sizeof(tmp), "%s: Ophalen FTD Mail mislukt!", date);
        g_free(date);
        gtk_statusbar_push(GTK_STATUSBAR(gui->mail->statusbar), 0, tmp);
        return FALSE;
    }

    if (numNewMail > 0) {
        g_timeout_add(1000, ftd_gui_mail_new_mail_blink, NULL);
    }

    snprintf(tmp, sizeof(tmp), "%s: Ophalen FTD Mail geslaagd - %i nieuw(e) bericht(en); %i berichten totaal", date, numNewMail, ftd_mail_get_num_messages());
    g_free(date);
    gtk_statusbar_push(GTK_STATUSBAR(gui->mail->statusbar), 0, tmp);

    ftd_gui_mail_treeOntvangen_update(NULL);
    ftd_gui_mail_treeVerzonden_update(NULL);

    return FALSE;
}

gboolean
ftd_gui_mail_callback_nieuw_clicked(GtkWidget *nop, gpointer data)
{
    g_assert(gui);
    g_assert(gui->mail);

    gtk_window_set_modal (GTK_WINDOW(gui->mail->window), FALSE);
    ftd_gui_message_new("", "", NULL, 0, NULL);

    return FALSE;
}

gboolean
ftd_gui_mail_callback_reageer_clicked(GtkWidget *nop, gpointer data)
{
    GtkTreeSelection *selection;
    GtkTreeIter iter;
    GtkTreeModel *model;

    g_assert(gui);
    g_assert(gui->mail);

    if (!gui->mail->selection) {
        ftd_gui_dialog_show(NULL, "Je dient eerst een bericht te selecteren alsvorens je een reply hierop kan geven.", gui->mail->window, FALSE);
        return FALSE;
    }

    model = GTK_TREE_MODEL(gui->mail->treestoreOntvangen);
    selection = gui->mail->selection;

    if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
        char *afzender;
        char *subject;
        char *nieuw_subject;
        FtdMailBericht *bericht;
        char *nieuw_bericht;

        gtk_tree_model_get (GTK_TREE_MODEL(model), &iter, 1, &afzender, 0, &subject, 3, &bericht, -1);

        if (strncmp(subject, "Re:", 3) == 0) {
            // Eenmaal "Re:" is voldoende.
            nieuw_subject = g_strdup(subject);
        } else {
            nieuw_subject = g_strdup_printf("Re: %s", subject);
        }

        // FIXME: Vervang <br /> door \n
        nieuw_bericht = g_strdup_printf("[quote=%s]%s[/quote]\n", afzender, ftd_string_value(bericht->body));

        ftd_gui_message_new(afzender, nieuw_subject, nieuw_bericht, 0, NULL);

        g_free(afzender);
        g_free(subject);
        g_free(nieuw_bericht);
        g_free(nieuw_subject);
    }

    return FALSE;
}

gboolean
ftd_gui_mail_callback_deleten_clicked(GtkWidget *nop, gpointer data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;
    GtkTreeSelection *selection = NULL;

    g_assert (gui);
    g_assert (gui->mail);

    switch (gtk_notebook_get_current_page(GTK_NOTEBOOK(gui->mail->notebook))) {
        case 0:
            selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->mail->treeOntvangen));
            break;
        case 1:
            selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->mail->treeVerzonden));
            break;
    }

    if (!selection) {
        return FALSE;
    }

    if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
        FtdMailBericht *bericht;

        gtk_tree_model_get (GTK_TREE_MODEL(model), &iter, 3, &bericht, -1);

        ftd_mail_delete(bericht);

        ftd_gui_mail_treeOntvangen_update(NULL);
        ftd_gui_mail_treeVerzonden_update(NULL);
    }

    return FALSE;
}

gboolean
ftd_gui_mail_callback_load_url(gpointer data)
{
    g_assert(gui);
    g_assert(gui->mail);

///#ifdef NO_EXTERNAL_BROWSER
#if 0
    g_print(__FILE__ ":%i Not yet implemented\n", __LINE__);
#else
    ftd_gui_browser_navigate(gui->mail->browser_data, HTML_MAIL_FILE);
#endif

    return FALSE;
}

gboolean
ftd_gui_mail_switch_page(GtkWidget *nop, GtkNotebookPage *page, guint pagenum, gpointer data)
{
    g_assert(gui);
    g_assert(gui->mail);

    if (pagenum == 0) {
        GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->mail->treeOntvangen));
        ftd_gui_mail_callback_treeOntvangen_changed(selection, NULL);
    } else {
        GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->mail->treeVerzonden));
        ftd_gui_mail_callback_treeVerzonden_changed(selection, NULL);
        gtk_widget_set_sensitive(gui->mail->cmdReageer, FALSE);
    }

    return FALSE;
}

void
ftd_gui_mail_auto_check_callback(gpointer data)
{
    gtk_button_clicked(GTK_BUTTON(gui->mail->cmdControleer));
}

gboolean
ftd_gui_mail_new_mail_blink(gpointer data)
{
    gboolean is_visible;
    static int state = 0;
    GdkPixbuf *pixbuf = NULL;

    g_object_get(gui->mail->window, "visible", &is_visible, NULL);

    if (is_visible) {
        // Herstel het icoon
        pixbuf = ftd_gui_main_get_pixbuf("icon-mail_off");
        gtk_image_set_from_pixbuf(GTK_IMAGE(gui->toolbar->imgMail), pixbuf);
        return FALSE;
    }

    if (state == 0) {
        pixbuf = ftd_gui_main_get_pixbuf("icon-mail_active");
        state = 1;
    } else {
        pixbuf = ftd_gui_main_get_pixbuf("icon-mail_off");
        state = 0;
    }

    gtk_image_set_from_pixbuf(GTK_IMAGE(gui->toolbar->imgMail), pixbuf);

    return TRUE;
}

static void
ftd_gui_mail_row_activated(GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data)
{
    ftd_gui_mail_callback_reageer_clicked(NULL, NULL);
}
