/*
 *  Copyright (C) 2000 Marco Pesenti Gritti
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/* Galeon includes */
#include "galeon.h"
#include "Gtm.h"
#include "mozilla.h"
#include "downloader.h"
#include "filepicker.h"
#include "misc.h"
#include "prefs.h"
#include "embed.h"

/* GNOME includes */
#include <libgnome/gnome-i18n.h>
#include <libgnome/gnome-exec.h>
#include <libgnomeui/gnome-dialog-util.h>
#include <liboaf/liboaf.h>
#include <libgnomevfs/gnome-vfs-utils.h>

static gboolean downloader_gtm_add_url (const gchar *url, gchar *dir, 
					gboolean disable_proxy,
					gboolean disable_auto_dl);
static void downloader_save_url_with_dir (const gchar *url, 
					  const char *directory);
static void downloader_save_url_without_dir (const gchar *url);
static void downloader_save_url_with_command_line (const gchar *url, 
						   const gchar *command,
						   const gchar *directory);
static void downloader_save_url_with_gtm (const gchar *url, 
					  const gchar *directory);

/**
 * save_link:
 */
void
downloader_save_link (GaleonEmbed *embed, const gchar *url)
{
	switch (eel_gconf_get_integer (CONF_DOWNLOADING_DOWNLOADER))
	{
	case DOWNLOADER_BUILTIN:
		save_url (embed, (gchar *)url, CONF_STATE_SAVE_DIR,
			  eel_gconf_get_boolean (CONF_DOWNLOADING_ASK_DIR),
			  FALSE, FALSE);
		break;
		
	case DOWNLOADER_GTM:
	case DOWNLOADER_EXTERNAL:
		downloader_save_url (url);
		break;
	}
}

/**
 * save_url
 */
void
downloader_save_url (const gchar *url)
{
	if (eel_gconf_get_boolean (CONF_DOWNLOADING_ASK_DIR))
	{
		gchar *dirName, *retPath = NULL;
		gboolean ret;

		dirName = eel_gconf_get_string (CONF_DOWNLOADING_DIR);
		if (!dirName)
		{
			dirName = g_strdup (g_get_home_dir());
		}

		ret = show_file_picker (NULL, _("Choose destination folder"),
				        dirName, NULL, modeGetFolder, &retPath,
				        NULL);
		if (ret == TRUE)
		{
			downloader_save_url_with_dir (url, retPath);
		}
		g_free (dirName);
		g_free (retPath);
	}
	else
	{
		downloader_save_url_without_dir (url);
	}
}

static void
downloader_save_url_with_dir (const gchar *url, const char *directory)
{
	Downloader downloader;
	gchar *command;

	/* which downloader? */
	downloader = eel_gconf_get_integer (CONF_DOWNLOADING_DOWNLOADER);
	if (downloader == DOWNLOADER_EXTERNAL)
	{
		/* get command */
		command = eel_gconf_get_string 
			(CONF_DOWNLOADING_EXTERNAL_COMMAND);

		/* check available */
		if (command != NULL)
		{
			/* check valid */
			if (strlen (command) > 0)
			{
				downloader_save_url_with_command_line 
					(url, command, directory);
				return;
			}

			/* free allocated string */
			g_free (command);
		}
	}

	/* fallthrough default */
	downloader_save_url_with_gtm (url, directory);
}

static void
downloader_save_url_without_dir (const gchar *url)
{
	Downloader downloader;
	gchar *command, *dir, *exp_dir;

	/* get directory to save to */
	dir = eel_gconf_get_string (CONF_DOWNLOADING_DIR);

	if (dir && strcmp(dir,"") == 0)
	{
		exp_dir = g_strdup (dir);
	}
	else if (dir)
	{
		exp_dir = gnome_vfs_expand_initial_tilde (dir);
		g_free (dir);
	}
	else
	{
		exp_dir = g_strdup (g_get_home_dir());
	}

	/* which downloader? */
	downloader = eel_gconf_get_integer (CONF_DOWNLOADING_DOWNLOADER);
	if (downloader == DOWNLOADER_EXTERNAL)
	{
		/* get command */
		command = eel_gconf_get_string 
		  (CONF_DOWNLOADING_EXTERNAL_COMMAND);

		/* check available */
		if (command != NULL)
		{
			/* check valid */
			if (strlen (command) > 0)
			{
				downloader_save_url_with_command_line 
					(url, command, exp_dir);
				g_free (command);
				g_free (exp_dir);
				return;
			}

			/* free allocated string */
			g_free (command);
		}
	}

	/* fallthrough default */
	downloader_save_url_with_gtm (url, exp_dir);

	g_free (exp_dir);
}

static void 
downloader_save_url_with_command_line (const gchar *url, const gchar *command,
				       const gchar *directory)
{
	gchar *partial_command, *full_command;
	gchar *text;	
	gint pid;

	partial_command = str_dup_replace (command, "%s", url);
	full_command = str_dup_replace (partial_command, "%f", directory);
	g_free (partial_command);
	
	if (eel_gconf_get_boolean (CONF_DOWNLOADING_EXTERNAL_TERMINAL))
	{
		char *argv[5] = { "gnome-terminal", "-t", 
				  _("Galeon Downloader"), "-e",
				 full_command };
		
		/* FIXME: this will only detect if the execution
		 * of gnome-terminal failed... */
		pid = gnome_execute_async (directory, 5, argv);	
	}
	else
	{
		int i;
		gchar **argv = g_strsplit (full_command, " ", 100);
		for (i=0; argv[i] != NULL; i++);

		pid = gnome_execute_async (directory, i, argv);
		g_strfreev (argv);
	}
	if (pid == -1)
	{
		text = g_strdup_printf (_("Failed to execute download "
					  "command:\n\"%s\""), full_command);
		g_warning (text);
		g_free (text);
	}

	g_free (full_command);
}

/**
 * save_url_with_gtm
 */
static void
downloader_save_url_with_gtm (const gchar *url, const gchar *directory)
{  
	gboolean auto_download;

	auto_download = eel_gconf_get_boolean (CONF_DOWNLOADING_AUTO_DOWNLOAD);
	downloader_gtm_add_url (strdup(url), (char *)directory,
				FALSE, !auto_download);
}

/*
 * Calls the gtm CORBA interface function gtm_add_url() to place the
 * download in queue
 */
static gboolean 
downloader_gtm_add_url (const gchar *url, gchar *dir, gboolean disable_proxy,
			gboolean disable_auto_dl)
{
	CORBA_Environment ev;
	extern CORBA_Environment corba_env;
	GTM_Download gtm_download_client;
	gboolean result;

	/* exception catching environment */
	CORBA_exception_init (&ev);

	result = FALSE;

	ev = corba_env;
	gtm_download_client =   
		oaf_activate_from_id ("OAFIID:GNOME_GTM", 
				      0, NULL, &ev);

	if (gtm_download_client != NULL)
	{
		result = GTM_Download_add_url ( gtm_download_client, url, dir,
						disable_proxy,
						disable_auto_dl, &ev);
		
		if (ev._major != CORBA_NO_EXCEPTION)
		{
			g_warning ("Exception thrown: %s\n", 
				   CORBA_exception_id (&ev));
			CORBA_exception_free (&ev);
		}
	}
	else
	{
		GtkWidget *dialog;
		gchar *text;

		text = g_strdup_printf (_("Failed to communicate with GTM.\n\n"
					  "Please check it is installed "
					  "correctly. Download it from:\n"
					  "\thttp://gtm.sourceforge.net"));
		dialog = gnome_error_dialog (text);
		gnome_dialog_run_and_close (GNOME_DIALOG (dialog));
		g_free (text);
	}
  
	return result;
}

