/* gcc soup-test.c -g -O0 -Wall -o soup-test `pkg-config --cflags --libs libsoup-2.4` && ./soup-test */

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

static GMainContext *main_context;
static GMainLoop *main_loop;
static SoupSession *session;
static int msg_counter = 0;

static gpointer
test_soup_thread (gpointer user_data)
{
	g_main_context_push_thread_default (main_context);
	g_main_loop_run (main_loop);
	g_main_context_pop_thread_default (main_context);

	/* abort any pending operations */
	soup_session_abort (session);

	g_object_unref (session);
	session = NULL;

	return NULL;
}

static void
message_got_cb (SoupSession *session,
		SoupMessage *msg,
		gpointer user_data)
{
	msg_counter++;
}

int
main (void)
{
	GThread *thread;
	int ii, wait_for_msg_counter = 0;

	main_context = g_main_context_new ();
	main_loop = g_main_loop_new (main_context, FALSE);

	thread = g_thread_new (NULL, test_soup_thread, NULL);

	session = soup_session_async_new_with_options (
		SOUP_SESSION_ASYNC_CONTEXT, main_context,
		SOUP_SESSION_MAX_CONNS, 1,
		NULL);

	for (ii = 0; ii < 100; ii++) {
		if (ii && !(ii % 5)) {
			SoupMessage *msg;

			while (msg_counter < wait_for_msg_counter) {
				g_usleep (100000);
			}

			wait_for_msg_counter = msg_counter + 1;

			msg = soup_message_new (SOUP_METHOD_GET, (msg_counter % 2) ? "http://www.gnome.org/index.html" : "http://www.redhat.com/index.html");
			soup_message_headers_append (msg->request_headers, "Connection", "close");
			soup_session_queue_message (session, msg, message_got_cb, NULL);
		} else {
			g_object_set ((GObject *) session, "proxy-resolver", NULL, NULL);
		}
	}

	g_main_loop_quit (main_loop);

	g_thread_join (thread);

	g_main_context_unref (main_context);
	g_main_loop_unref (main_loop);

	return 0;
}
