/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * Copyright (C) 2009 Arnout Vandecappelle (Essensium/Mind) <arnout@mind.be>
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <glib.h>
#include <libsoup/soup.h>

#include "test-utils.h"

static void
got_headers_cb (SoupMessage *msg, GMainLoop *loop)
{
	debug_printf (1, "Got headers - was not expected.\n");
	errors++;
	if (loop)
		g_main_loop_quit (loop);
}

static void
got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk, GMainLoop *loop)
{
	debug_printf (1, "Got chunk - was not expected.\n");
	errors++;
	if (loop)
		g_main_loop_quit (loop);
}

static void
got_body_cb (SoupMessage * msg, GMainLoop *loop)
{
	debug_printf (1, "Got body - was not expected.\n");
	errors++;
	if (loop)
		g_main_loop_quit (loop);
}

static void
finished_cb (SoupMessage *msg, GMainLoop *loop)
{
	debug_printf (2, "Finished.\n");
	if (loop)
		g_main_loop_quit (loop);
}

static void
response_cb (SoupSession *session, SoupMessage *msg, GMainLoop *loop)
{
	debug_printf (2, "Got response %d: %s.\n", msg->status_code, msg->reason_phrase);
	if (loop)
		g_main_loop_quit (loop);
}

static gboolean
timeout_cb (gpointer user_data)
{
	GMainLoop *loop = user_data;
	debug_printf (1, "Timed out.\n");
	g_main_loop_quit (loop);
	return FALSE;
}

static void
do_request (void)
{
	SoupURI *uri;
	SoupMessage *msg;
	GMainLoop *loop;
	SoupSession *session;

	loop = g_main_loop_new (NULL, TRUE);
	if (!loop) {
		debug_printf (1, "Failed to start GMainLoop\n");
		return;
	}
	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);

	uri = soup_uri_new ("http://1.1.1.1/"); /* IANA reserved, shouldn't reply. */
	msg = soup_message_new_from_uri ("GET", uri);
	soup_uri_free (uri);

	g_signal_connect (msg, "got_headers", G_CALLBACK (got_headers_cb), loop);
	g_signal_connect (msg, "got_body", G_CALLBACK (got_body_cb), loop);
	g_signal_connect (msg, "got_chunk", G_CALLBACK (got_chunk_cb), loop);
	g_signal_connect (msg, "finished", G_CALLBACK (finished_cb), loop);
	soup_session_queue_message (session, msg, (SoupSessionCallback) response_cb, loop);

	g_timeout_add_seconds(1, timeout_cb, loop);

	g_main_loop_run (loop);

	g_object_add_weak_pointer (G_OBJECT (session), (gpointer *)&session);

	soup_session_abort (session);
	g_object_unref (session);

	/* Make sure idle_run_queue is properly dispatched. */
	while (g_main_context_iteration (NULL, FALSE))
		debug_printf (1, "Dispatched some events while stopping.\n");

	if (session) {
		errors++;
		debug_printf (1, "leaked SoupSession!\n");
		g_object_remove_weak_pointer (G_OBJECT (session), (gpointer *)&session);
	}

	g_main_loop_unref (loop);
	loop = NULL;
}


int
main (int argc, char **argv)
{
	test_init (argc, argv, NULL);

	do_request ();

	test_cleanup ();
	return errors != 0;
}
