/* ====================================================================
 * 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 "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"
#ifdef WIN32
#include <windows.h>
#endif

void
ftd_gui_center_new(void)
{
    GtkWidget *label;
    FtdGuiCenter *center = (FtdGuiCenter *) g_malloc0(sizeof(FtdGuiCenter));

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

    center->widget = gtk_notebook_new ();

    gtk_notebook_set_scrollable(GTK_NOTEBOOK(center->widget), TRUE);

    gtk_paned_pack2(GTK_PANED(gui->worksheet->widget), gui->worksheet->center->widget, TRUE, TRUE);

    gtk_widget_show (center->widget);

    if (ftd_config_get()->toonIRCClient) {
        ftd_gui_center_irc_new();
        gtk_container_add (GTK_CONTAINER (center->widget), center->irc->widget);

        label = gtk_label_new ("IRC Client");
        gtk_widget_show (label);
        gtk_notebook_set_tab_label (GTK_NOTEBOOK (center->widget), center->irc->widget, label);
        gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);
    }

    ftd_gui_center_eventlist_new();

    g_signal_connect(center->widget, "switch-page", G_CALLBACK(ftd_gui_center_switch_page), NULL);
}

void
ftd_gui_center_switch_page(GtkNotebook *notebook, GtkNotebookPage *page, guint pagenum, gpointer data)
{
    g_assert(gui);
    g_assert(gui->worksheet);

    /* Alleen in het geval van de watchlist moeten we de gegevens updaten */
    if (gui->worksheet->center->watchlist) {
        // Zoek de tab waar de watchlist op vermeld staat en activeer deze
        if (gtk_notebook_get_nth_page(GTK_NOTEBOOK (gui->worksheet->center->widget), pagenum) == gui->worksheet->center->watchlist->widget) {
            // Ververs de gegevens
///#ifndef NO_EXTERNAL_BROWSER
#if 1
            ftd_gui_center_watchlist_create();
#endif
            ftd_gui_center_watchlist_show(NULL, NULL);
        }
    }
}

void
ftd_gui_center_launch_browser(char *url_unquoted)
{
    char *url = g_shell_quote(url_unquoted);
    char cmd[1024];
#ifdef WIN32
    char cmd_tmp[1024];
    HKEY key, subkey;
    char* buff;
    FtdString *tmp, *browser;
    LONG size;
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    RegOpenKeyA(HKEY_CLASSES_ROOT, "HTTP" , &key);
    RegOpenKeyA(key, "shell", &subkey);
    RegCloseKey(key);
    key = subkey;
    RegOpenKeyA(key, "open", &subkey);
    RegCloseKey(key);
    key = subkey;
    RegOpenKeyA(key, "command", &subkey);
    RegCloseKey(key);

    RegQueryValueA(subkey, NULL, NULL, &size);
    buff = (char *) g_malloc(sizeof(char) * size);  // note: '\0' already included in size
    RegQueryValueA(subkey, NULL, buff, &size);
    /* buff bevat nu iets in de trand van C:\PROGRA~1\MOZILL~1\FIREFOX.EXE -url "%1"
       de %1 moet vervangen worden door een %s. */
    tmp = ftd_string_new(buff);
    g_free(buff);

    browser = ftd_string_replace(tmp, "\"%1\"", "%s");
    ftd_string_free(tmp);
    tmp = browser;

    /* De GLib instructie g_spawn_command_line_async werkt niet lekker
       onder Windows..dan maar op de WIN32 manier... */
    browser = ftd_string_replace(tmp, " ", "\" \"");
    ftd_string_free(tmp);
    tmp = browser;

    snprintf(cmd_tmp, sizeof(cmd_tmp), ftd_string_value(browser), url_unquoted);
    snprintf(cmd, sizeof(cmd), "\"%s\"", cmd_tmp);
    ftd_string_free(browser);

    RegCloseKey(subkey);

    if(!CreateProcessA( NULL,   // No module name (use command line).
        cmd, // Command line.
        NULL,             // Process handle not inheritable.
        NULL,             // Thread handle not inheritable.
        FALSE,            // Set handle inheritance to FALSE.
        0,                // No creation flags.
        NULL,             // Use parent's environment block.
        NULL,             // Use parent's starting directory.
        &si,              // Pointer to STARTUPINFO structure.
        &pi))             // Pointer to PROCESS_INFORMATION structure.
    {
        g_print( "CreateProcess failed (%d).\n", GetLastError() );
    }
#elif defined(DARWIN)
    GError *error = NULL;

    snprintf(cmd, sizeof(cmd), "open %s", url);
    g_spawn_command_line_async(cmd, &error);
    if (error) {
        g_print("%s: %s\n", error->message, cmd);
    }
#else
    GError *error = NULL;

    if (g_getenv("GNOME_DESKTOP_SESSION_ID") && g_find_program_in_path("gnome-open")) {
        // We draaien Gnome
        snprintf(cmd, sizeof(cmd), "gnome-open %s", url);
    } else if (g_getenv("KDE_FULL_SESSION") && g_find_program_in_path("kfmclient")) {
        // We draaien KDE
        snprintf(cmd, sizeof(cmd), "kfmclient openURL %s", url);
    } else if (g_getenv("BROWSER")) {
        // XFCE4 gebruikt de environment variabele BROWSER om de standaardbrowser te bepalen.
        snprintf(cmd, sizeof(cmd), "%s %s", g_getenv("BROWSER"), url);
    } else {
        // Window manager onbekend..probeer firefox, mozilla of konqueror te lanceren indien aanwezig
        if (g_find_program_in_path("firefox")) {
            snprintf(cmd, sizeof(cmd), "firefox %s", url);
        } else if (g_find_program_in_path("mozilla")) {
            snprintf(cmd, sizeof(cmd), "mozilla %s", url);
        } else if (g_find_program_in_path("konqueror")) {
           snprintf(cmd, sizeof(cmd), "konqueror %s", url);
        } else {
            ftd_gui_dialog_show(NULL, "Kan geen bruikbare externe browser vinden.", gui->window, TRUE);
            g_free(url);
            return;
        }
    }

    g_spawn_command_line_async(cmd, &error);
    if (error) {
        g_print("%s: %s\n", error->message, cmd);
    }
#endif

    g_free(url);
}
