/* gcc -g -O2 -Wall `pkg-config --cflags --libs libsoup-2.4` test2.c -o test2 && ./test2 */

#include <stdio.h>
#include <string.h>
#include <libsoup/soup.h>

static GMainLoop *loop;
static SoupSession *soup_session;

static void
authenticate_cb (SoupSession *sess,
		 SoupMessage *msg,
		 SoupAuth *auth,
		 gboolean retrying,
		 gpointer data)
{
	printf ("   %s: retrying:%d\n", __FUNCTION__, retrying);

	if (!retrying)
		soup_auth_authenticate (auth, "mcrha", "password");
}

static gboolean queue_message_idle_cb (gpointer user_data);
static void
queue_cb (SoupSession *session,
	  SoupMessage *msg,
	  gpointer user_data)
{
	gint counter = GPOINTER_TO_INT (user_data);
	printf ("   > %s: [%d]: result:%d\n", __FUNCTION__, counter, msg->status_code);
	if (counter < 2) {
		counter++;
		g_idle_add (queue_message_idle_cb, GINT_TO_POINTER (counter));
	} else {
		g_main_loop_quit (loop);
	}
}

static gboolean
queue_message_idle_cb (gpointer user_data)
{
	SoupMessage *message;
	gint counter = GPOINTER_TO_INT (user_data);
	static const char *body = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
		"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
		"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
		"<SOAP-ENV:Header><types:RequestServerVersion xmlns:types=\"http://schemas.microsoft.com/exchange/services/2006/types\" Version=\"Exchange2007_SP1\"/>"
		"</SOAP-ENV:Header><SOAP-ENV:Body xmlns:messages=\"http://schemas.microsoft.com/exchange/services/2006/messages\"><messages:GetFolder xmlns=\"http://schemas.microsoft.com/exchange/services/2006/types\">"
		"<messages:FolderShape><BaseShape>Default</BaseShape></messages:FolderShape><messages:FolderIds><DistinguishedFolderId Id=\"inbox\"/></messages:FolderIds></messages:GetFolder></SOAP-ENV:Body></SOAP-ENV:Envelope>";

	message = soup_message_new ("POST", "https://exchange.example.com/EWS/Exchange.asmx");
	soup_message_set_request (message, "text/xml; charset=utf-8", SOUP_MEMORY_STATIC, body, strlen (body));
	printf ("%s: [%d]: to be send\n", __FUNCTION__, counter);
	soup_session_queue_message (soup_session, message, queue_cb, GINT_TO_POINTER (counter));
	//g_object_unref (message);

	return FALSE;
}

int main (void)
{
	g_type_init ();

	loop = g_main_loop_new (NULL, FALSE);
	soup_session = soup_session_async_new ();
	g_signal_connect (soup_session, "authenticate", G_CALLBACK (authenticate_cb), NULL);

	g_object_set (G_OBJECT (soup_session), SOUP_SESSION_USE_NTLM, TRUE, NULL);

	/*{
	SoupLogger *logger;
	logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);
	soup_session_add_feature (soup_session, SOUP_SESSION_FEATURE (logger));
	}*/

	g_idle_add (queue_message_idle_cb, GINT_TO_POINTER (0));
	g_main_loop_run (loop);
	g_main_loop_unref (loop);

	g_object_unref (soup_session);

	return 0;
}
