/* so-client.c
 *
 * Copyright (C) 2002-2005 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 <bonobo/bonobo-main.h>
#include <bonobo-activation/bonobo-activation.h>
#include <libgnomeui/gnome-ui-init.h>
#include <libecal/e-cal-component.h>

#include "sunone-connection.h"

static void
display_components (icalcomponent *icalcomp)
{
	icalcomponent_kind kind;
	icalcomponent *subcomp;
	ECalComponent *comp;
	const char *uid;
	ECalComponentText summary;

	kind = icalcomponent_isa (icalcomp);
	if (kind != ICAL_VCALENDAR_COMPONENT) {
		g_print ("ERROR: icalcomponent is not a VCALENDAR file");
		return;
	}

	subcomp = icalcomponent_get_first_component (icalcomp, ICAL_ANY_COMPONENT);
	while (subcomp) {
		comp = e_cal_component_new ();
		kind = icalcomponent_isa (subcomp);
		switch (kind) {
		case ICAL_VEVENT_COMPONENT :
			e_cal_component_set_icalcomponent (comp, icalcomponent_new_clone (subcomp));
			e_cal_component_get_uid (comp, &uid);
			e_cal_component_get_summary (comp, &summary);
			g_print ("VEVENT %s\n\tSummary:%s\n", uid, summary.value);
			break;
		case ICAL_VTODO_COMPONENT :
			e_cal_component_set_icalcomponent (comp, icalcomponent_new_clone (subcomp));
			e_cal_component_get_uid (comp, &uid);
			e_cal_component_get_summary (comp, &summary);
			g_print ("VTODO %s\n\tSummary:%s\n", uid, summary.value);
		default :
			break;
		}

		g_object_unref (G_OBJECT (comp));
		subcomp = icalcomponent_get_next_component (icalcomp, ICAL_ANY_COMPONENT);
	}
}

static gboolean
test_calendar_cb (gpointer user_data)
{
	icalcomponent *icalcomp;
	guint error_code;
	SunOneConnection *cnc = (SunOneConnection *) user_data;

	error_code = sunone_connection_fetchcomponents_by_lastmod (
		cnc, "user", icaltime_null_time (), icaltime_null_time (), TYPE_ALL, 
		REQUEST_ALL, &icalcomp, NULL);
	if (SUNONE_ERROR_IS_SUCCESSFUL (error_code)) {
		display_components (icalcomp);
	}

	bonobo_main_quit ();
	return FALSE;
}

int
main (int argc, char *argv[])
{
	SunOneConnection *cnc;

	gnome_program_init ("so-client", VERSION, 
				LIBGNOMEUI_MODULE, 
				argc, argv, 
				GNOME_PROGRAM_STANDARD_PROPERTIES, NULL);
	bonobo_init_full (&argc, argv, 
			bonobo_activation_orb_get(), 
			CORBA_OBJECT_NIL, 
			CORBA_OBJECT_NIL);

	cnc = sunone_connection_new("http://sampras.prc.sun.com:8080", "http://webcache.prc.sun.com:8080", "user", "passwd");

	if (!SUNONE_ERROR_IS_SUCCESSFUL (sunone_connection_login (cnc))) {
		g_error ("Could not establish connection to SunOne server");
		g_object_unref (G_OBJECT (cnc));
	}

	g_idle_add ((GSourceFunc) test_calendar_cb, cnc);

	bonobo_main ();

	return 0;
}
