#include <stdlib.h>
#include <stdio.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 UnityWebappsContext *observer_context = NULL;

static const gchar * const locations[] = {"Foo", "Bar", "Baz", NULL};
static gint location_index = 0;

static void
observer_context_location_changed (UnityWebappsContext *context, gint interest_id, const gchar *location, gpointer user_data)
{
  if (g_strcmp0 (locations[location_index], location) != 0)
    {
      printf("Got incorrect location: %s\n", location);
      exit(1);
    }
  location_index++;

  
  if (locations[location_index] == NULL)
    {
      uwa_emit_test_finished ();
    }
}

static gboolean
change_location (gpointer user_data)
{
  UnityWebappsContext *context;
  
  context = (UnityWebappsContext *)user_data;
  
  unity_webapps_context_set_view_location (context, locations[location_index]);
  
  return TRUE;
}

static void
create_observer_context (UnityWebappsContext *context)
{
  observer_context = unity_webapps_context_new_for_context_name (service, unity_webapps_context_get_context_name (context));
  
  unity_webapps_context_on_view_location_changed (observer_context, observer_context_location_changed, NULL);
}
  


static void
context_one_ready (UnityWebappsContext *context, gpointer user_data)
{
  create_observer_context (context);
  
  g_timeout_add (100, change_location, context);
}




gint
main (gint argc, gchar **argv)
{
  g_type_init ();
  
  service = unity_webapps_service_new ();
  
  unity_webapps_context_new (service, "Test", "test.ts", ICON_URL, NULL, context_one_ready, NULL);
  
  mainloop = g_main_loop_new (NULL, FALSE);
  
  g_main_loop_run (mainloop);
  
  return 0;  
}
