/* 
 * Test case to show bug in soup_request_send_async.
 * When async-coiintext property is set to non-default GMainContext, 
 * sendRequestCallback is not called. It works properly with default 
 * GMainContext
 */
#include <glib.h>

#define LIBSOUP_USE_UNSTABLE_REQUEST_API
#include <libsoup/soup-request-http.h>
#include <libsoup/soup-requester.h>

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

#define USE_DEFAULT 0 //set this to 1 to use default GMainContext

    static void
gotHeadersCallback(SoupMessage* msg, gpointer data)
{
    printf("\n$$$$$ IN [%s] $$$$$\n", __FUNCTION__);
}

    static void
sendRequestCallback(GObject* source, GAsyncResult* res, gpointer userData)
{
    printf("\n$$$$$ IN [%s] $$$$$\n", __FUNCTION__);
}

    int
main()
{
    if (!g_thread_supported())
        g_thread_init(NULL);

    g_type_init();

#if USE_DEFAULT==1   
    GMainContext *context = g_main_context_default();
#else
    GMainContext *context = g_main_context_new();
#endif
    g_main_context_push_thread_default(context);
    GMainLoop *loop = g_main_loop_new(context, FALSE);

    SoupSession* session = soup_session_async_new_with_options(SOUP_SESSION_ASYNC_CONTEXT,
            g_main_context_get_thread_default(), NULL);

    if (!soup_session_get_feature(session, SOUP_TYPE_REQUESTER)) {
        SoupRequester* requester = soup_requester_new();
        soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester));
        g_object_unref(requester);
    }

    SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(session, SOUP_TYPE_REQUESTER));
    SoupRequest *request = soup_requester_request(requester, "http://107.108.99.197/test_1.html", NULL);
    SoupMessage *soupMessage = soup_request_http_get_message(SOUP_REQUEST_HTTP(request));

    g_signal_connect(soupMessage, "got-headers", G_CALLBACK(gotHeadersCallback), NULL);

    soup_request_send_async(request, g_cancellable_new(), sendRequestCallback, 0);

    g_main_loop_run(loop);
}
