#include <stdlib.h>

#include "unity-webapps-service.h"
#include "unity-webapps-context.h"
#include "uwa-test-client.h"

#define ICON_URL "http://www.ubuntu.com/sites/www.ubuntu.com/files/active/02_ubuntu/U_homepage/picto-desktop.png"

static GMainLoop *mainloop = NULL;
static UnityWebappsService *service = NULL;
  
static void
context_prepared (UnityWebappsContext *context, gpointer user_data)
{
  g_assert(0 && "should not get there");
}

static gboolean
done_with_test (gpointer user_data)
{
  uwa_emit_test_finished ();
  return FALSE;
}

/**
 *
 * Validates that the context ready callback is NOT called if in the meantime
 * a context destroyed has been called.
 * The test is a bit timing dependant (in the prepare -> destroy sequence) but
 * tries to simulate someone navigating to an integrated website and very quickly
 * (before the loop -> context-daemon -> libunity-webapps context read -> js completes)
 * navigates away (changes the url). The js callback should not be called in this case.
 * 
 */
gint
main (gint argc, gchar **argv)
{
  g_type_init ();

  service = unity_webapps_service_new ();

  UnityWebappsContext *
    context = unity_webapps_context_new_lazy (service, "Test", "test.ts", ICON_URL, NULL);
  unity_webapps_context_prepare(context, context_prepared, NULL);
  unity_webapps_context_destroy(context, TRUE);

  // 5 seconds is kind of arbitrary, trying to make sure that the context-daemon has the time
  // to come back to libunity-webapps & trigger the callback (or not)
  g_timeout_add_seconds (5, done_with_test, context);

  mainloop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (mainloop);

  return 0;  
}
