/*
 *  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.
 */

#include "galeon.h"
#include "misc.h"
#include "embed.h"
#include "glade.h"
#include "bookmarks.h"
#include "prefs.h"
#include "mozilla.h"

#include <string.h>
#include <gtk/gtktogglebutton.h>
#include <gtk/gtkspinbutton.h>
#include <gtk/gtktable.h>
#include <libgnome/gnome-config.h>
#include <libgnome/gnome-i18n.h>

/* local function prototypes */
void new_user_druid_finish_cb (GtkWidget *widget, gpointer dummy);
void new_user_druid_cancel_cb (GtkWidget *widget, gpointer dummy);
gboolean new_user_druid_delete_event_cb (GtkWidget *widget, GdkEventAny *event,
					 gpointer dummy);
void new_user_druid_create_smart_bookmarks_check_button_toggled_cb 
(GtkWidget *toggle);
static void add_smart (BookmarkItem *parent, gchar *name, gchar *nick,
		       gchar *url, gchar *pixmap_file, gchar *notes);
static void add_bookmarklets (BookmarkItem *parent);

/**
 * new_user_druid_finish_cb: called when the user gets to the end of
 * the introductory druid and clicks on finish.
 */
void
new_user_druid_finish_cb (GtkWidget *widget, gpointer dummy)
{
	static const gchar *galeon_show = "galeon \"%s\"";
	GtkWidget *dialog;
	gint i;
	
	/* values fetched from widgets */
	gboolean import_netscape_bookmarks_checked;
	gboolean import_mozilla_bookmarks_checked;
	gboolean import_netscape_preferences_checked;
	gboolean create_smart_bookmarks_checked;
	gboolean google_web_checked;
	gboolean google_groups_checked;
	gboolean dogpile_checked;
	gboolean yahoo_checked;
	gboolean dictionary_checked;
	gboolean freshmeat_checked;
	gboolean rpmfind_checked;
	gboolean debian_packages_checked;
	gboolean bugzilla_checked;
	gboolean stock_quotes_checked;
	gboolean imdb_movies_checked;
	gboolean google_images_checked;
	gboolean bookmarklets_checked;
	gboolean http_checked;
	gboolean https_checked;
	gboolean ghelp_checked;
	gboolean ftp_checked;
	gboolean file_checked;
	gchar *http_proxy_site;
	gchar *ssl_proxy_site;
	gchar *ftp_proxy_site;
	gint http_proxy_port;
	gint ssl_proxy_port;
	gint ftp_proxy_port;
	
	/* lookup table for check buttons */
	const struct { gchar *name; gboolean *state; } check_lookups[] = {
		{ "new_user_druid_import_netscape_bookmarks_radio_button",
		  &import_netscape_bookmarks_checked, },
		{ "new_user_druid_import_mozilla_bookmarks_radio_button",
		  &import_mozilla_bookmarks_checked, },
		{ "new_user_druid_import_netscape_preferences_check_button",
		  &import_netscape_preferences_checked, },
		{ "new_user_druid_create_smart_bookmarks_check_button",
		  &create_smart_bookmarks_checked, },
		{ "new_user_druid_google_web_check_button",
		  &google_web_checked, },
		{ "new_user_druid_google_groups_check_button",
		  &google_groups_checked, },
		{ "new_user_druid_dogpile_check_button",
		  &dogpile_checked, },
		{ "new_user_druid_yahoo_check_button",
		  &yahoo_checked, },
		{ "new_user_druid_dictionary_check_button",
		  &dictionary_checked, },
		{ "new_user_druid_freshmeat_check_button",
		  &freshmeat_checked, },
		{ "new_user_druid_rpmfind_check_button",
		  &rpmfind_checked, },
		{ "new_user_druid_debian_packages_check_button",
		  &debian_packages_checked, },
		{ "new_user_druid_bugzilla_check_button",
		  &bugzilla_checked, },
		{ "new_user_druid_stock_quotes_check_button",
		  &stock_quotes_checked, },
		{ "new_user_druid_imdb_movies_check_button",
		  &imdb_movies_checked, },
		{ "new_user_druid_google_images_check_button",
		  &google_images_checked, },
		{ "new_user_druid_bookmarklets_check_button",
		  &bookmarklets_checked, },
		{ "new_user_druid_http_check_button",
		  &http_checked, },
		{ "new_user_druid_https_check_button",
		  &https_checked, },
		{ "new_user_druid_ftp_check_button",
		  &ftp_checked, },
		{ "new_user_druid_ghelp_check_button",
		  &ghelp_checked, },
		{ "new_user_druid_file_check_button",
		  &file_checked, },
		{ NULL, NULL }/* terminator, must be last */
        };
	
	/* lookup table for string entry fields */
	const struct { gchar *name; gchar **value; } edit_lookups[] = {
		{ "new_user_http_proxy_site", &http_proxy_site },
		{ "new_user_ssl_proxy_site",  &ssl_proxy_site },
		{ "new_user_ftp_proxy_site",  &ftp_proxy_site },
		{ NULL, NULL }/* terminator, must be last */
	};
	
	/* lookup table for spin entrys */
	const struct { gchar *name; gint *value; } spin_lookups[] = {
		{ "new_user_http_proxy_port", &http_proxy_port },
		{ "new_user_ssl_proxy_port",  &ssl_proxy_port },
		{ "new_user_ftp_proxy_port",  &ftp_proxy_port },
		{ NULL, NULL }/* terminator, must be last */
	};
	
	/* lookup all the widgets in the list */
	for (i = 0; check_lookups[i].name != NULL; i++)
	{
		GtkWidget *check;
		
		/* find the checkbutton widget */
		check = glade_lookup_widget (widget, check_lookups[i].name);
		
		/* get it's state and store it */
		*(check_lookups[i].state) = gtk_toggle_button_get_active
			(GTK_TOGGLE_BUTTON (check));
	}
	
	/* lookup all the widgets in the list */
	for (i = 0; edit_lookups[i].name != NULL; i++)
	{
		GtkWidget *edit;
		
		/* find the entry widget */
		edit = glade_lookup_widget (widget, edit_lookups[i].name);
		
		/* get all the text into a new string */
		*(edit_lookups[i].value) = 
			gtk_editable_get_chars (GTK_EDITABLE (edit), 0, -1);
	}
	
	/* lookup all the widgets in the list */
	for (i = 0; spin_lookups[i].name != NULL; i++)
	{
		GtkWidget *spin;
		
		/* find the spinbutton widget */
		spin = glade_lookup_widget (widget, spin_lookups[i].name);
		
		/* get the value as an int */
		*(spin_lookups[i].value) = 
			gtk_spin_button_get_value_as_int 
			(GTK_SPIN_BUTTON (spin));
	}
	
	/* get preferences from netscape */
	if (import_netscape_preferences_checked)
	{
		netscape_import_prefs ();
	}
	
	/* create smart bookmarks toolbar */
	if (create_smart_bookmarks_checked)
	{
		BookmarkItem *toolbar;
		gchar* utfstr;

		/* create the toolbar */
		utfstr = mozilla_locale_to_utf8(_("Smart Bookmarks Toolbar"));
		toolbar = bookmarks_new_bookmark 
			(BM_FOLDER, TRUE, utfstr,
			 NULL, NULL, NULL, NULL);
		g_free(utfstr);
		toolbar->create_toolbar = TRUE;
		toolbar->toolbar_style = TOOLBAR_STYLE_HORIZONTAL;
		
		/* add it into the root folder */
		bookmarks_root->list = 
			g_list_append (bookmarks_root->list, toolbar);
		toolbar->parent = bookmarks_root;
		
		/* add each smart bookmark checked */
		if (google_web_checked)
		{
			/* URL marked as translatable so you can add the
			 * appropriate lang= bits to get the results in the
			 * right language (normally detection is done at
			 * the google homepage I think -- MattA) */
			add_smart (toolbar, "Google", "google",
				   _("http://www.google.com/search?q=%s"),
				   SHARE_DIR "/google.png", NULL);
		}
		if (google_groups_checked)
		{
			add_smart (toolbar, "Usenet", "news",
				   "http://groups.google.com/groups?q=%s"
				   "&meta=site%3Dgroups", 
				   SHARE_DIR "/google_groups.png", NULL);
		}
		if (dogpile_checked)
		{
			add_smart (toolbar, "Dogpile", "dogpile",
				   "http://search.dogpile.com/texis/search"
				   "?q=%s&geo=no&fs=web&av=custom&"
				   "engines=goto&engines=looksmart&"
				   "engines=thunderstone&engines=findwhat&"
				   "engines=sprinks&engines=directhit&"
				   "engines=google&engines=infoseek&"
				   "engines=lycos&engines=kanoodle&"
				   "engines=opendir&engines=realnames&"
				   "engines=altavista&engines=yahoo",
				   NULL, NULL);
		}
		if (yahoo_checked)
		{
			add_smart (toolbar, "Yahoo!", "yahoo",
				   "http://search.yahoo.com/bin/search?p=%s",
				   NULL, NULL);
		}
		if (dictionary_checked)
		{
			/* URL marked as translatable so that non-English
			 * dictionaries can be used -- don't forget to
			 * make the equivalent change in the glade file */
			add_smart (toolbar, _("Dictionary"), "dict",
				   /* xgettext: no-c-format */
				   _("http://www.m-w.com/cgi-bin/"
				     "dictionary?va=%s"), NULL, NULL);
		}
		if (bugzilla_checked)
		{
			add_smart (toolbar, "Bug #", "bug",
				   "http://bugzilla.gnome.org/"
				   "show_bug.cgi?id=%s", 
				   SHARE_DIR "/bug.png", NULL);
		}
		if (freshmeat_checked)
		{
			add_smart (toolbar, "Freshmeat", "fm",
				   "http://freshmeat.net/search?q=%s",
				   SHARE_DIR "/freshmeat.png", NULL);
		}
		if (rpmfind_checked)
		{
			add_smart (toolbar, "RPMFind", "rpm",
				   "http://rpmfind.net/linux/rpm2html/"
				   "search.php?query=%s",
				   SHARE_DIR "/rpm.png", NULL);
		}
		if (debian_packages_checked)
		{
			add_smart (toolbar, "Debian", "deb",
				   "http://packages.debian.org/cgi-bin/"
				   "search_packages.pl?keywords=%s&"
				   "searchon=names&subword=1&version=all&"
				   "release=all", 
				   SHARE_DIR "/debian.png", NULL);
		}
		if (google_images_checked)
		{
			add_smart (toolbar, "Images", "img",
				   "http://images.google.com/images?q=%s",
				   SHARE_DIR "/google_images.png", NULL);
		}
		if (stock_quotes_checked)
		{
			add_smart (toolbar, "Stocks", "st",
				   "http://finance.yahoo.com/q?s=%s"
				   "&d=c&k=c4&t=1d",
				   SHARE_DIR "/stocks.png", NULL);
		}
		if (imdb_movies_checked)
		{
			add_smart (toolbar, "IMDb", "imdb",
				   "http://www.imdb.com/Find?%s", 
				   SHARE_DIR "/imdb_movies.png", NULL);
		}
		if (bookmarklets_checked)
		{
			add_bookmarklets (toolbar);
		}
	}
	
	/* import bookmarks */
	if (import_netscape_bookmarks_checked)
	{
  	        /* FIXME: dont use this callback directly! */
	        bookmarks_import_netscape_activate_cb (NULL, NULL);
	}
	if (import_mozilla_bookmarks_checked)
	{
  	        /* FIXME: dont use this callback directly! */
	        bookmarks_import_mozilla_activate_cb (NULL, NULL);
	}
	
	/* set URL handlers as requested */
	gnome_config_push_prefix ("/Gnome/URL Handlers/");
	if (http_checked)
	{
		gnome_config_set_string ("http-show", galeon_show);
	}
	if (https_checked)
	{
		gnome_config_set_string ("https-show", galeon_show);
	}
	if (ghelp_checked)
	{
		gnome_config_set_string ("ghelp-show", galeon_show);
	}
	if (ftp_checked)
	{
		gnome_config_set_string ("ftp-show", galeon_show);
	}
	if (file_checked)
	{
		gnome_config_set_string ("file-show", galeon_show);
	}
	gnome_config_pop_prefix ();
	
	/* setup proxies */
	if (http_proxy_site != NULL && strlen (http_proxy_site) > 0)
	{
		eel_gconf_set_integer(CONF_NETWORK_PROXY_MODE
				      , 1);
		eel_gconf_set_string (CONF_NETWORK_HTTP_PROXY
				      , http_proxy_site);
		eel_gconf_set_string (CONF_NETWORK_SSL_PROXY
				      ,  ssl_proxy_site);
		eel_gconf_set_string (CONF_NETWORK_FTP_PROXY
				      ,  ftp_proxy_site);
	        eel_gconf_set_integer(CONF_NETWORK_HTTP_PROXY_PORT
				      , http_proxy_port);
		eel_gconf_set_integer(CONF_NETWORK_SSL_PROXY_PORT
				      ,  ssl_proxy_port);
		eel_gconf_set_integer(CONF_NETWORK_FTP_PROXY_PORT
				      ,  ftp_proxy_port);
	}
	
	/* kill the dialog */
	dialog = glade_lookup_widget (widget, "new_user_druid");
	gtk_widget_destroy (GTK_WIDGET (dialog));
	
	/* save all the initial settings */
	bookmarks_tb_dirty = TRUE;
	bookmarks_updated ();
	
	/* create an initial window if needed */
	if (g_list_length (all_windows) == 0)
	{
		embed_create_default (NULL, TRUE);
	}
}

/**
 * new_user_druid_cancel_cb: called when the user cancels the druid
 * using the buttons provided.
 */
void
new_user_druid_cancel_cb (GtkWidget *widget, gpointer dummy)
{
	GtkWidget *dialog;
	
	/* kill the dialog */
	dialog = glade_lookup_widget (widget, "new_user_druid");
	gtk_widget_destroy (GTK_WIDGET (dialog));
	
	/* create an initial window if needed */
	if (g_list_length (all_windows) == 0)
	{
		embed_create_default (NULL, TRUE);
	}
}

/**
 * new_user_druid_delete_event_cb: called when the user closes the 
 * druid with a window manager delete event.
 */
gboolean
new_user_druid_delete_event_cb (GtkWidget *widget, GdkEventAny *event,
				gpointer dummy)
{
	/* create an initial window if needed */
	if (g_list_length (all_windows) == 0)
	{
		embed_create_default (NULL, TRUE);
	}
	
	/* still destroy the druid window */
	return FALSE;
}

/**
 * new_user_druid_create_smart_bookmarks_check_button_toggled_cb: turn a list
 * of options on and off when the user toggles a master switch.
 */
void
new_user_druid_create_smart_bookmarks_check_button_toggled_cb 
(GtkWidget *toggle)
{
	GtkWidget *options_frame;
	gboolean sensitive;
	
	/* find the new state */
	sensitive = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (toggle));
	
	/* find the frame containing the list of options */
	options_frame = 
		glade_lookup_widget (GTK_WIDGET (toggle), 
				     "new_user_druid_smart_bookmarks_list");
	
	/* set the frame sensitivity, this will set all children too */
	gtk_widget_set_sensitive (GTK_WIDGET (options_frame), sensitive);
}

/**
 * add_smart: add a bookmark to the smart bookmarks toolbar
 */
static void
add_smart (BookmarkItem *parent, gchar *name, gchar *nick, 
	   gchar *url, gchar *pixmap_file, gchar * notes)
{
	BookmarkItem *site;
	gchar* utfstr;
	
	utfstr = mozilla_locale_to_utf8(name);
	/* create the bookmarks */
	site = bookmarks_new_bookmark (BM_SITE, TRUE, utfstr, url, nick, notes, 
				       pixmap_file);
	g_free(utfstr);
	
	/* add it to the toolbar */
	parent->list = g_list_append (parent->list, site);
	site->parent = parent;
}

/**
 * add_bookmarklets: add some bookmarklets
 */
static void 
add_bookmarklets (BookmarkItem *parent)
{
	gint i;
	BookmarkItem *root;
	BookmarkItem *item;
	static const struct
	{ 
		gchar *name;
		gchar *url;  
	} bookmarklets[] = {
		{ N_("More Bookmarklets"), "http://www.bookmarklets.com/" }, 
		{ "separator", NULL },
		{ N_("More Info About..."), "javascript:if(frames.length>0){F=' (Open frame in new window first.)'}else{F=''}Q=document.getSelection();if(!Q){void(Q=prompt('No text selected on page.'+F+'\\n\\nKeywords...?',''))};if(Q)location.href='http://bookmarklets.com/moreinfo.phtml?q='+escape(Q)" },
		{ "separator", NULL },
		{ N_("Zoom on First Image..."), "javascript:if(document.images.length<1){alert('No image!')}else{D0iB=document.images[0];sZ2T=prompt('Resize by..','1.5');if(sZ2T){with(document){write('<img src='+D0iB.src+' width='+sZ2T*D0iB.width+' height='+sZ2T*D0iB.height+'>');close()}}}void(null)" },
		{ N_("Page Color..."), "javascript:if(frames.length<1){var c0l=prompt('Change to which background color?','');if (c0l != null) void(document.bgColor=c0l)}else{alert('Page has frames. Use the version of this bookmarklet for frames. (bookmarklets.com)')}" },
		{ "separator", NULL },
		{ N_("Scroll Page (very slow)"), "javascript:var wN2sc8Rl;Sa5gNA9k=new Function('clearTimeout(wN2sc8Rl)');document.onkeydown=Sa5gNA9k;Sa5gNA9k();void(wN2sc8Rl=setInterval('if(pageYOffset<document.height-innerHeight){window.scrollBy(0,1)}else{Sa5gNA9k()}',150))" },
		{ N_("Scroll Page (slow)"), "javascript:var wN2scRl;Sa5gNA9k=new Function('clearTimeout(wN2scRl)');document.onkeydown=Sa5gNA9k;Sa5gNA9k();void(wN2scRl=setInterval('if(pageYOffset<document.height-innerHeight){window.scrollBy(0,1)}else{Sa5gNA9k()}',50))" },
		{ N_("Scroll Page (fast)"), "javascript:var wN2scRl;Sa5gNA9k=new Function('clearTimeout(wN2scRl)');document.onkeydown=Sa5gNA9k;Sa5gNA9k();void(wN2scRl=setInterval('if(pageYOffset<document.height-innerHeight){window.scrollBy(0,2)}else{Sa5gNA9k()}',50))" },
		{ N_("Scroll Page (very fast)"), "javascript:var wN2scRl;Sa5gNA9k=new Function('clearTimeout(wN2scRl)');document.onkeydown=Sa5gNA9k;Sa5gNA9k();void(wN2scRl=setInterval('if(pageYOffset<document.height-innerHeight){window.scrollBy(0,10)}else{Sa5gNA9k()}',50))" },
		{ N_("Scroll Page... (variable)"), "javascript:var wN2scRl;S3g=new Function('clearTimeout(wN2scRl)');document.onkeydown=S3g;a7T=prompt('Rate...','');if(a7T!=null){S3g();void(wN2scRl=setInterval('if(pageYOffset<document.height-innerHeight){scrollBy(0,a7T)}else{S3g()}',50))}else{void(null)}" },
		{ "separator", NULL },
		{ N_("Page Freshness?"), "javascript:if(frames.length<1){alert('The server indicates that the page was last modified: ' + window.document.lastModified)}else{alert('Page is framed. Use version of bookmarklet for frames. (bookmarklets.com)')}" },
		{ N_("Go To Selected URL"), "javascript:if(frames.length>0){alert('Frames!')}else{ulBV3pQy=document.getSelection();if(ulBV3pQy!=''){location.href=ulBV3pQy.replace(/\\042/g,'').replace(/\\047/g,'').replace(/\\s/g,'')}else{alert('Select text on page like:\\n   http://www.domain.com...')}}" },
		{ N_("Duplicate Page"), "javascript:dT30FfN3b=new Date();void(window.open(location.href,'w'+dT30FfN3b.getTime()))" },
		{ N_("Set In-Page Bookmark"), "javascript:void(InPageBookmark=pageYOffset)" },
		{ N_("Go To In-Page Bookmark"), "javascript:if (typeof InPageBookmark=='undefined'){alert('No in-page bookmark. Use Set In-Page Bookmark tool. (bookmarklets.com)')}else{scrollBy(0,InPageBookmark-pageYOffset)}" },
		{ "separator", NULL },
		{ N_("Read Cookie for Site"), "javascript:if(document.cookie.length<1){alert('No cookie for this site.')}else{alert('Cookie for this site: '+document.cookie)}" },
		{ N_("AutoFill Anonymous"), "javascript:function ROIoiW(){var i=0,j,A='anonymous',D,E,F=document.forms;while(i<F.length){E=F[i].elements;for(j=0;j<E.length;j++){D=E[j];if(D.type=='text'){D.value=(D.name.toUpperCase().indexOf('MAIL')!=-1)?A+'@example.com':A}}i++}}ROIoiW();void(null)" },
		{ N_("Translate to English"), "javascript:void(location.href='http://translate.google.com/translate?hl=en&u='+location.href)"},
		{ NULL, NULL}
	};
	gchar* utfstr;

	utfstr = mozilla_locale_to_utf8(_("Bookmarklets"));
	root = bookmarks_new_bookmark (BM_FOLDER, TRUE, utfstr,
				       NULL, NULL, NULL, NULL);
	g_free(utfstr);
	
	parent->list = g_list_append (parent->list, root);
	root->parent = parent;
	root->create_context_menu = TRUE;
	
	for (i = 0; bookmarklets[i].name != NULL; i++)
	{
		if (bookmarklets[i].url == NULL)
		{
			item = bookmarks_new_bookmark 
				(BM_SEPARATOR, FALSE, NULL, NULL, NULL, NULL,
				 NULL);
		}
		else
		{
			utfstr= mozilla_locale_to_utf8(_(bookmarklets[i].name));
			item = bookmarks_new_bookmark
				(BM_SITE, TRUE, utfstr,
				 bookmarklets[i].url, NULL, NULL, NULL);
			g_free(utfstr);
		}

		item->parent = root;
		root->list = g_list_append (root->list, item);
	}
}

