/* main.c
 *
 * Copyright (C) 2002-2004 Sun Microsystems, Inc
 *
 * AUTHORS
 *     Jack Jia <jack.jia@sun.com>
 *     Harry Lu <harry.lu@sun.com>
 *     Alfred Peng <alfred.peng@sun.com>
 *     Rodrigo Moya <rodrigo@ximian.com>
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h>
#include <glib/gi18n.h>
#include <libbonobo.h>
#include <libgnomeui/libgnomeui.h> 
#include <libgnomevfs/gnome-vfs.h>
#include <glade/glade.h>
#include <gconf/gconf-client.h>
#include <libsoup/soup.h>
#include <e-util/e-icon-factory.h>
#include <libedataserverui/e-passwords.h>
#include <libedata-cal/e-data-cal-factory.h>
#include <camel/camel.h>

#include "cal-backend-wcap.h"
#include "cal-backend-wcap-factory.h"
#include "sunone-component.h"
#include "sunone-offline-listener.h"

#define CLEAN_WCAP 0

static EDataCalFactory *calendar_factory = NULL;
char *evolution_dir;
static BonoboGenericFactory *component_factory = NULL;
SunOneComponent *global_sunone_component;

static BonoboObject *
sunone_component_factory (BonoboGenericFactory *factory,
			const char *component_id, void *component)
{
	g_return_val_if_fail (strcmp (component_id, SUNONE_COMPONENT_IID) == 0, NULL);

	return component;
}

static gboolean
setup_component_factory (void)
{
	global_sunone_component = sunone_component_new ();

	component_factory = bonobo_generic_factory_new (SUNONE_COMPONENT_FACTORY_IID,
				sunone_component_factory,
				global_sunone_component);

	return TRUE;
}

static void
last_calendar_gone_cb (EDataCalFactory *factory, gpointer data)
{
	/* Remove the bonobo_main_quit in order to fix bug 4937958 */
}

static gboolean
setup_calendar (void)
{	
	/* setup calendar factory */
	g_message ("Setting up calendar factory...\n");
	calendar_factory = e_data_cal_factory_new ();
	if (!calendar_factory) {
		g_warning ("\nCould not create the calendar factory\n");
		return FALSE;
	}

	e_data_cal_factory_register_backend (calendar_factory,
			(g_object_new (events_backend_wcap_factory_get_type(), NULL)));
	e_data_cal_factory_register_backend (calendar_factory,
			(g_object_new (tasks_backend_wcap_factory_get_type(), NULL)));

	if (!e_data_cal_factory_register_storage (calendar_factory, "OAFIID:GNOME_Evolution_SunOneStorage_CalendarFactory")) {
		bonobo_object_unref (BONOBO_OBJECT (calendar_factory));
		calendar_factory = NULL;
		g_warning ("\nCould not register the calendar factory\n");
		return FALSE;
	}

	g_signal_connect (G_OBJECT (calendar_factory),
			    "last_calendar_gone",
			    G_CALLBACK (last_calendar_gone_cb),
			    NULL);
	return TRUE;
}

#if CLEAN_WCAP

static void
remove_group (ESourceList *source_list)
{
	const char *base_uri;
	GSList *groups, *p, *to_delete = NULL;

	groups = e_source_list_peek_groups (source_list); 
	for (p = groups; p != NULL; p = g_slist_next (p)) {
		ESourceGroup *group = E_SOURCE_GROUP (p->data);
		base_uri = e_source_group_peek_base_uri (group);
		if (strncmp (base_uri, "wcap://", 7) == 0) {
			to_delete = g_slist_append (to_delete, group);
		}
	}

	for (p = to_delete; p!= NULL; p = g_slist_next (p)) {
		ESourceGroup *group = E_SOURCE_GROUP (p->data);
		e_source_list_remove_group (source_list, group);
	}
	e_source_list_sync (source_list, NULL);

	g_slist_free (to_delete);
}

static void
remove_wcap_esources ()
{
	char *conf_key_cals = "/apps/evolution/calendar/sources";
	char *conf_key_tasks = "/apps/evolution/tasks/sources";
	ESourceList *source_list_cal, *source_list_task;

	source_list_cal = e_source_list_new_for_gconf_default (
					conf_key_cals);
	source_list_task = e_source_list_new_for_gconf_default (
					conf_key_tasks);
	
	remove_group (source_list_cal);
	remove_group (source_list_task);

	g_object_unref (source_list_cal);
	g_object_unref (source_list_task);
}
#endif

int
main (int argc, char *argv[])
{
	GnomeClient *master_client;
	SunOneOfflineListener *offline_listener = NULL;

	bindtextdomain (GETTEXT_PACKAGE, EVOLUTION_LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	g_message ("Initializing evolution-jescs...\n");

	g_thread_init (NULL);

	gnome_program_init (PACKAGE, VERSION, LIBGNOMEUI_MODULE, argc, argv, GNOME_PROGRAM_STANDARD_PROPERTIES, 
				GNOME_PARAM_HUMAN_READABLE_NAME, _("Sun JESCS Connector"), NULL);

	bonobo_init_full (&argc, argv,
			  bonobo_activation_orb_get(),
			  CORBA_OBJECT_NIL,
			  CORBA_OBJECT_NIL);
	
	gnome_vfs_init ();
	glade_init ();
	e_icon_factory_init ();

	evolution_dir = g_build_filename (g_get_home_dir (), ".evolution", NULL);
#if 0
	camel_init (evolution_dir, FALSE);
#endif
	e_passwords_init ();
	sunone_message_init ();

#if CLEAN_WCAP
	/* remove trash esources if possible */	
	remove_wcap_esources ();
#endif

	/* evolution-jescs should not be restarted by session manager */
	master_client = gnome_master_client ();
	gnome_client_set_restart_style (master_client, GNOME_RESTART_NEVER);

	if (!setup_component_factory ())
		goto failed;
	if (!setup_calendar ())
		goto failed;

	offline_listener = sunone_offline_listener_new (calendar_factory);
	sunone_component_set_offline_listener (global_sunone_component,
					offline_listener);

	/* run the application */
	g_message ("Evolution-jescs up and running!\n");
	if (getenv ("EVOLUTION_JESCS_VERBOSE_DEBUG")) {
                /* Redirect stderr to stdout and make it line-buffered
                 * rather than block-buffered, for ease of debug
                 * redirection.
                 */
                dup2 (STDOUT_FILENO, STDERR_FILENO);
                setvbuf (stdout, NULL, _IOLBF, 0);
                setvbuf (stderr, NULL, _IOLBF, 0);
                printf ("EVOLUTION_JESCS_VERBOSE_DEBUG=1\n");
        }

	bonobo_main ();

	e_passwords_shutdown ();
#if CLEAN_WCAP
	remove_wcap_esources ();
#endif

	return 0;

failed:
	g_warning ("Could not register jescs calendar backend services.\n This probably mean another copy of evolution-jescs is already running.\n");

	return 1;
}
