/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/***************************************************************************
 *            test-kolab-util-cal-freebusy.c
 *
 *  Thu Aug 12 14:27:45 2010
 *  Copyright  2010  Christian Hilberg
 *  <hilberg@kernelconcepts.de>
 ****************************************************************************/

/*
 * 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.1 of the License, 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301,  USA
 */

/*----------------------------------------------------------------------------*/

#define _GNU_SOURCE
#include <string.h>

#include <fcntl.h>
#include <sys/types.h>

#include <glib.h>
#include <stdlib.h>

#include <camel/camel-kolab-stream.h>
#include <camel/camel-kolab-session.h>

#include <libecal/e-cal-component.h>

#include <libekolabutil/camel-system-headers.h>
#include <libekolabutil/kolab-util-camel.h>
#include <libekolabutil/kolab-util-http.h>
#include <libekolabutil/kolab-util-cal-freebusy.h>
#include <libekolabutil/kolab-util-glib.h>

/*----------------------------------------------------------------------------*/

#define TESTCASE "test-kolab-util-cal-freebusy"
#define AUTH "auth"
#define SECURITY "security"

#define TRIGGER KOLABCONV_FB_TYPE_TRIGGER
#define FBL_IFB KOLABCONV_FB_TYPE_IFB
#define FBL_VFB KOLABCONV_FB_TYPE_VFB
#define FBL_XFB KOLABCONV_FB_TYPE_XFB

/*----------------------------------------------------------------------------*/

typedef struct _KolabITestFB {
	gchar *out_fn;
	gchar *out_cfgkey;
	gchar *cmp_fn;
	gchar *cmp_cfgkey;
	CamelStream *out_fs;
	CamelStream *cmp_fs;
} KolabITestFB;

/*----------------------------------------------------------------------------*/

static void
kolab_itest_fb_init (KolabITestFB *kitfb, GKeyFile *key_file)
{
	GError *tmp_err = NULL;

	kitfb->out_fn = g_key_file_get_string (key_file,
	                                       TESTCASE,
	                                       kitfb->out_cfgkey,
	                                       NULL);
	kitfb->cmp_fn = g_key_file_get_string (key_file,
	                                       TESTCASE,
	                                       kitfb->cmp_cfgkey,
	                                       NULL);
	g_assert (kitfb->out_fn != NULL);
	g_assert (kitfb->cmp_fn != NULL);
	/* open filestreams */
	kitfb->out_fs = camel_kolab_stream_new_filestream (kitfb->out_fn,
	                                                   O_RDWR|O_CREAT|O_TRUNC,
	                                                   0600,
	                                                   &tmp_err);
	g_assert (kitfb->out_fs != NULL); /* means tmp_err is NULL */
	/* TODO use this for result comparison
	 * kitfb->cmp_fs = camel_kolab_stream_new_filestream (kitfb->cmp_fn,
	 *                                                    O_RD,
	 *                                                    NULL);
	 *  g_assert (kitfb->cmp_fs != NULL);
	 */
}

static void
kolab_itest_fb_uninit (KolabITestFB *kitfb)
{
	camel_kolab_stream_free (kitfb->out_fs);
	/* camel_kolab_stream_free (kitfb->cmp_fs); */
	g_free (kitfb->out_fn);
	g_free (kitfb->out_cfgkey);
	g_free (kitfb->cmp_fn);
	g_free (kitfb->cmp_cfgkey);
}

static gboolean
test_kolab_util_cal_freebusy (void)
{
	KolabUtilHttpJob *job = NULL;
	ECalComponent *ecalcomp = NULL;
	gsize nbytes = 0;
	gssize obytes = 0;
	gchar *config = NULL;
	gchar *url_string = NULL;
	gchar *username = NULL;
	gchar *password = NULL;
	gchar *pkcs11pin = NULL;
	gchar *calobj = NULL;
	GKeyFile *key_file = NULL;
	gboolean ok = FALSE;
	GError *tmp_err = NULL;

	gint ii = 0;

	KolabITestFB kitfb[KOLABCONV_FB_LASTTYPE];

	/* set config keys */
	kitfb[TRIGGER].out_cfgkey = g_strdup ("trg_out_fn");
	kitfb[TRIGGER].cmp_cfgkey = g_strdup ("trg_cmp_fn");

	kitfb[FBL_IFB].out_cfgkey = g_strdup ("ifb_out_fn");
	kitfb[FBL_IFB].cmp_cfgkey = g_strdup ("ifb_cmp_fn");

	kitfb[FBL_VFB].out_cfgkey = g_strdup ("vfb_out_fn");
	kitfb[FBL_VFB].cmp_cfgkey = g_strdup ("vfb_cmp_fn");

	kitfb[FBL_XFB].out_cfgkey = g_strdup ("xfb_out_fn");
	kitfb[FBL_XFB].cmp_cfgkey = g_strdup ("xfb_cmp_fn");

	/* init subsystems */
	kolab_util_glib_init ();
	kolab_util_http_init ();
	/* libcamel
	 *
	 * Curl init may configure the underlying SSL lib,
	 * but as far as SSL goes, we want Camel to rule here
	 *
	 * TODO check whether Camel session needs to be
	 *      initialized before or after libcurl
	 *
	 */
	ok = kolab_util_camel_init (&tmp_err);
	if (! ok) {
		g_warning ("%s: %s", __func__, tmp_err->message);
		g_error_free (tmp_err);
		return FALSE;
	}

	/* get config */
	key_file = g_key_file_new ();

	config = g_strdup (TESTCASE ".conf");
	g_return_val_if_fail (g_key_file_load_from_file (key_file, config, G_KEY_FILE_NONE, NULL), FALSE);

	for (ii = 0; ii < KOLABCONV_FB_LASTTYPE; ii++)
		kolab_itest_fb_init (&(kitfb[ii]), key_file);

	url_string = g_key_file_get_string (key_file, TESTCASE, "url", NULL);
	username = g_key_file_get_string (key_file, AUTH, "username", NULL);
	password = g_key_file_get_string (key_file, AUTH, "password", NULL);
	pkcs11pin = g_key_file_get_string (key_file, SECURITY, "pkcs11pin", NULL);

	g_return_val_if_fail (url_string != NULL, FALSE);
	g_return_val_if_fail (username != NULL, FALSE);
	g_return_val_if_fail (password != NULL, FALSE);
	g_return_val_if_fail (pkcs11pin != NULL, FALSE);

	/* create KolabUtilHttpJob */
	job = kolab_util_http_job_new ();
	job->passwd = password;
	job->pkcs11pin = pkcs11pin;

	/* create CamelURL object */
	job->url = camel_url_new (url_string, 0);
	g_assert (job->url != NULL);

	/* set username for basic auth */
	camel_url_set_user (job->url, username);

	g_free (url_string);
	g_free (username);

	/* job.buffer must be initialized NULL (no storage allocated!) */
	job->buffer = NULL;

	/* send trigger request, then the requests for the [ivx]fb entries */
	for (ii = 0; ii < KOLABCONV_FB_LASTTYPE; ii++) {
		ecalcomp = kolab_cal_util_fb_new_ecalcomp_from_request (job, ii, &tmp_err);
		if (tmp_err != NULL) {
			g_debug ("%s: %s [%s]",
			         __func__,
			         "error getting ECalComponent",
			         tmp_err->message);
			g_error_free (tmp_err);
			tmp_err = NULL;
		}
		/* write ecalcomp to file */
		calobj = NULL;
		nbytes = 0;
		if (ecalcomp != NULL) {
			g_debug ("%s: read %d bytes", __func__, job->nbytes);
			calobj = e_cal_component_get_as_string (ecalcomp);
		}
		if (calobj != NULL) {
			nbytes = strlen (calobj);
			/* output object */
			g_debug ("\n-------------------\n%s\n-------------------\n",
			         calobj);
			/* write to file */
			obytes = camel_stream_write (kitfb[ii].out_fs,
			                             calobj,
			                             nbytes,
			                             NULL,
			                             &tmp_err);
			if (tmp_err == NULL) {
				g_debug ("%s: wrote %d bytes", __func__, obytes);
			} else {
				/* TODO break test execution here */
				g_warning ("%s: %s",
				           __func__, tmp_err->message);
				g_free (tmp_err);
				tmp_err = NULL;
			}
			g_free (calobj);
		}
		kolab_cal_util_fb_ecalcomp_free (ecalcomp);
		/* TODO check result file */
	}

	/* cleanup */
	for (ii = 0; ii < KOLABCONV_FB_LASTTYPE; ii++)
		kolab_itest_fb_uninit (&(kitfb[ii]));

	kolab_util_http_job_free (job);
	g_key_file_free (key_file);
	g_free (config);

	/* shutdown subsystems */
	kolab_util_glib_shutdown ();
	kolab_util_http_shutdown ();

	/* libcamel */
	/* ATTN camel_shutdown () currently segfaults when NSS
	 *      is using openCryptoki infrastructure. Be sure
	 *      to call camel_kolab_session_shutdown() only
	 *      after all other libs have been shut down
	 */
	ok = kolab_util_camel_shutdown (&tmp_err);
	if (! ok) {
		g_warning ("%s: %s", __func__, tmp_err->message);
		g_error_free (tmp_err);
	}

	return TRUE;
}

/*----------------------------------------------------------------------------*/

gint
main (gint argc, gchar **argv)
{
	gboolean ok = FALSE;

	(void)argc;
	(void)argv;

	ok = test_kolab_util_cal_freebusy ();
	if (! ok)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}

/*----------------------------------------------------------------------------*/
