/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) version 3.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with the program; if not, see <http://www.gnu.org/licenses/>  
 *
 *
 * Authors:
 *		Srinivasa Ragavan <sragavan@novell.com>
 *
 * Copyright (C) 2009 Novell, Inc. (www.novell.com)
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

#include <config.h>

#include <gtk/gtk.h>
#include <glade/glade.h>
#include <glib/gi18n.h>
#include <misc/e-cursors.h>
#include <libedataserverui/e-passwords.h>
#include <mail/mail-mt.h>
#include "mail-shell.h"
#include <libgnome/gnome-sound.h>
#include <gconf/gconf-client.h>
#include <e-util/e-icon-factory.h>

#ifdef G_OS_WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#if HAVE_UNIQUE
#include <unique/unique.h>
#endif

#if HAVE_ANERLEY
#include <clutter-gtk/clutter-gtk.h>
#include <nbtk/nbtk.h>
#endif

gboolean windowed = FALSE;
gboolean anjal_icon_decoration = FALSE;
gboolean default_app =  FALSE;
GtkWidget *main_window;
static gchar **remaining_args;

/* For testing propose use the local (not installed) glade file */
/* #define GLADE_FILE PACKAGE_DATA_DIR"/anjal/glade/anjal.glade" */
#define GLADE_FILE "anjal.glade"

#define GCONF_KEY_MAILTO_ENABLED "/desktop/gnome/url-handlers/mailto/enabled"
#define GCONF_KEY_MAILTO_COMMAND "/desktop/gnome/url-handlers/mailto/command"
#define ANJAL_MAILTO_COMMAND "anjal %s"

#if HAVE_UNIQUE
static UniqueResponse
mail_message_received_cb (UniqueApp         *app,
                         gint               command,
                         UniqueMessageData *message_data,
                         guint              time_,
                         gpointer           user_data)
{
	 gchar *url;
	 GtkWindow *window = (GtkWindow *) user_data;
	 char *args[2];
	 
	 switch (command) {
	 case UNIQUE_ACTIVATE :
		  gtk_window_deiconify (window);
		  gtk_window_present (window);
		  return UNIQUE_RESPONSE_OK;

	 case UNIQUE_NEW :
		  return UNIQUE_RESPONSE_OK;

	 case UNIQUE_OPEN :
		  url = unique_message_data_get_text (message_data);
		  args[0] = url;
		  args[1] = NULL;
		  mail_shell_set_cmdline_args ((MailShell *)window, args);
		  mail_shell_handle_cmdline ((MailShell *)window);
		  g_free (url);
		  gdk_window_raise (((GtkWidget *)window)->window);
		  gtk_window_deiconify (window);
		  gtk_window_present (window);

		  return UNIQUE_RESPONSE_OK;
	 }

	 return UNIQUE_RESPONSE_PASSTHROUGH;
}

#endif

static void
check_and_set_default_mail (void)
{
	GConfClient *client = gconf_client_get_default ();
	gchar *mailer;
	printf("coming here\n");
	mailer  = gconf_client_get_string(client, GCONF_KEY_MAILTO_COMMAND, NULL);
	if (mailer && *mailer && (strcmp (mailer, ANJAL_MAILTO_COMMAND) == 0))
		return; /* Anjal is the default mailer */
	
	gconf_client_set_bool(client, GCONF_KEY_MAILTO_ENABLED, TRUE, NULL);
	gconf_client_set_string(client, GCONF_KEY_MAILTO_COMMAND, ANJAL_MAILTO_COMMAND, NULL);
	g_object_unref (client);
	printf("Set %s\n", GCONF_KEY_MAILTO_COMMAND);
}

static gboolean
idle_cb (MailShell *shell)
{
	if (default_app) {
		check_and_set_default_mail ();
	}

	return FALSE;
}

#ifdef G_OS_WIN32
static void
set_paths (void)
{
	wchar_t exe_filename[MAX_PATH];
	wchar_t *p;
	gchar *exe_folder_utf8;
	gchar *components_folder_utf8;
	gchar *top_folder_utf8;
	gchar *path;

	GetModuleFileNameW (NULL, exe_filename, G_N_ELEMENTS (exe_filename));

	p = wcsrchr (exe_filename, L'\\');
	g_assert (p != NULL);

	*p = L'\0';
	exe_folder_utf8 = g_utf16_to_utf8 (exe_filename, -1, NULL, NULL, NULL);

	p = wcsrchr (exe_filename, L'\\');
	g_assert (p != NULL);

	*p = L'\0';
	top_folder_utf8 = g_utf16_to_utf8 (exe_filename, -1, NULL, NULL, NULL);
	components_folder_utf8 =
		g_strconcat (top_folder_utf8,
#ifdef EVOLUTION_2_26
			     "/lib/evolution/2.26/components",
#else
			     "/lib/evolution/2.28/components",
#endif
			     NULL);

	path = g_build_path (";",
			     exe_folder_utf8,
			     components_folder_utf8,
			     g_getenv ("PATH"),
			     NULL);
	if (!g_setenv ("PATH", path, TRUE))
		g_warning ("Could not set PATH for Anjal and its child processes");

	g_free (path);
	g_free (exe_folder_utf8);
	g_free (components_folder_utf8);

	/* Set BONOBO_ACTIVATION_PATH */
	if (g_getenv ("BONOBO_ACTIVATION_PATH" ) == NULL) {
		path = g_build_filename (top_folder_utf8,
					 "lib/bonobo/servers",
					 NULL);
		if (!g_setenv ("BONOBO_ACTIVATION_PATH", path, TRUE))
			g_warning ("Could not set BONOBO_ACTIVATION_PATH");
		g_free (path);
	}
	g_free (top_folder_utf8);
}
#endif

int
main (int argc, char *argv[])
{
	GError *error = NULL;
#if HAVE_UNIQUE	
	UniqueApp *app;
#endif

	if (!g_thread_supported ()) 
		g_thread_init (NULL);
#ifdef G_OS_WIN32
	extern void link_shutdown (void);
	set_paths ();
#endif

	
	static GOptionEntry entries[] = {
    		{ "windowed", 'w', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_NONE, &windowed,N_("Run Anjal in a window"), NULL },
		{ "default-mailer", 'd', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_NONE, &default_app,N_("Make Anjal the default email client"), NULL },
		{ G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &remaining_args, NULL, NULL },
		{ NULL }
 	 	};

#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	
	gtk_set_locale ();

#if HAVE_ANERLEY
	if (!gtk_clutter_init_with_args (&argc, &argv, _("Anjal email client"), entries, NULL, &error)) {
		g_error ("Unable to start Anjal: %s\n", error->message);
		g_error_free(error);
	}
	nbtk_style_load_from_file (nbtk_style_get_default (), PACKAGE_DATA_DIR G_DIR_SEPARATOR_S "anerley" G_DIR_SEPARATOR_S "style.css", NULL);

#else
	if (!gtk_init_with_args (&argc, &argv, _("Anjal email client"), entries, NULL, &error)) {
		g_error ("Unable to start Anjal: %s\n", error->message);
		g_error_free(error);
	}
#endif	
	glade_init ();
	e_cursors_init ();
	e_passwords_init();
	e_icon_factory_init ();
	gtk_icon_theme_append_search_path (gtk_icon_theme_get_default(), PACKAGE_DATA_DIR G_DIR_SEPARATOR_S "anjal" G_DIR_SEPARATOR_S "icons");
	if (!g_thread_supported ()) 
		g_thread_init (NULL);
	mail_msg_init ();
	gnome_sound_init ("localhost");

#if HAVE_UNIQUE	
	app = unique_app_new ("org.gnome.Anjal", NULL);
	  if (unique_app_is_running (app))  {
		   gboolean cmd_line =  (remaining_args && remaining_args[0] != NULL);
		   
		  if (!cmd_line)
			unique_app_send_message (app, UNIQUE_ACTIVATE, NULL);
		  else {
			  UniqueMessageData *data = unique_message_data_new ();
			  unique_message_data_set_text (data, remaining_args[0], -1);
			  unique_app_send_message (app, UNIQUE_OPEN, data);
			  unique_message_data_free (data);
		  }

		  return 0;
	  }
#endif
	if (windowed)
		anjal_icon_decoration = TRUE;

	main_window = (GtkWidget *)mail_shell_new ();
	gtk_widget_show (main_window);
	mail_shell_set_cmdline_args ((MailShell *)main_window, remaining_args);
#if HAVE_UNIQUE
	g_signal_connect (app, "message-received",
                    G_CALLBACK (mail_message_received_cb),  main_window);
#endif
	
	g_idle_add ((GSourceFunc) idle_cb, main_window);

	gtk_main ();
	e_icon_factory_shutdown ();
	gnome_sound_shutdown ();
	e_cursors_shutdown ();
	
#ifdef G_OS_WIN32
	link_shutdown ();
#endif
	return 0;
}

#ifndef HACK
gpointer em_format_html_print_new(gpointer p1, int i)
{
	return NULL;
}

void em_format_html_print_raw_message (gpointer p1, gpointer p2)
{
	return ;
}

void 
eab_merging_book_commit_contact ()
{
}
void 
e_searching_tokenizer_set_primary_case_sensitivity ()
{
}
void 
eab_prompt_save_dialog ()
{
}
void
eab_merging_book_add_contact ()
{
}
void
e_searching_tokenizer_match_count ()
{
}
void
addressbook_load_cancel()
{
}
void
e_searching_tokenizer_new ()
{
}
void
e_searching_tokenizer_set_primary_search_string()
{
}
void
addressbook_load()
{
}
void
eab_load_error_dialog()
{
}

#endif
