#include <glib.h>
#include <glib/gstdio.h>
#include "unity-webapps-dpkg-available-application.h"
#include "unity-webapps-local-available-application.h"
#include "unity-webapps-policy-authorizer.h"
#include "unity-webapps-application-repository.h"
#include "unity-webapps-script-loader.h"
#include "unity-webapps-debug.h"

static GMainLoop *main_loop = NULL;

static void
print_userscript_contents (UnityWebappsApplicationRepository *repository, const gchar *app)
{
  gchar *contents;

  contents = unity_webapps_application_repository_get_userscript_contents (repository, app);
  g_message("Userscript contents: %s \n", contents);
  g_free (contents);
}

static void
install_response (UnityWebappsApplicationRepository *repository,
		  const gchar *name,
		  UnityWebappsApplicationStatus status,
		  gpointer user_data)
{
  g_message("Found application: %s \n", name);
  
  switch (status)
    {
    case UNITY_WEBAPPS_APPLICATION_STATUS_AVAILABLE:
      g_message("Application available for install \n");
      break;
    case UNITY_WEBAPPS_APPLICATION_STATUS_INSTALLED:
      g_message("Application installed \n");
      break;
    default:
      g_assert_not_reached ();
    }
}

int
main (int argc, gchar **argv)
{
  UnityWebappsApplicationRepository *repository;
  const GList *names, *name;
  UnityWebappsApplicationStatus status;

  g_type_init ();

  unity_webapps_debug_initialize_flags ();
  
  repository = unity_webapps_application_repository_new_default ();
  unity_webapps_application_repository_prepare (repository);

  names = unity_webapps_application_repository_resolve_url (repository, argv[1]);

      g_message("looked up application: %s \n", argv[1]);
  for (name = names; name != NULL; name = name->next)
    {
      const gchar * curname = (gchar *) name->data;

      g_message("application: %s \n", curname);
      status =
        unity_webapps_application_repository_get_resolved_application_status (repository,
                                                                              curname);
      
      g_message("Found application: %s \n", curname);
      
      switch (status)
        {
        case UNITY_WEBAPPS_APPLICATION_STATUS_AVAILABLE:
          g_message("Application available for install \n");
          unity_webapps_application_repository_install_application (repository, curname, install_response, NULL);
          break;
        case UNITY_WEBAPPS_APPLICATION_STATUS_INSTALLED:
          g_message("Application installed \n");
          //          print_userscript_contents (repository, curname);
          break;
        default:
          g_assert_not_reached ();
        }
    }
  g_list_free_full ((GList*) names, g_free);

  main_loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (main_loop);
  
  return 0;
}
