#include <gio/gio.h>

#include "unity-webapps-application-manifest.h"
#include "unity-webapps-local-available-application.h"
#include "unity-webapps-script-loader.h"
#include "unity-webapps-debug.h"

typedef struct _AvailableApplicationTestFixture {
  UnityWebappsLocalAvailableApplication *app;
  UnityWebappsScriptLoader *script_loader;
} AvailableApplicationTestFixture;

static void
setup_fixture_simple (AvailableApplicationTestFixture *fixture,
                      gconstpointer user_data)
{
  fixture->app = 
    (UnityWebappsLocalAvailableApplication *) unity_webapps_local_available_application_new (
        unity_webapps_application_manifest_new_from_file (
            TESTDATADIR "test-manifest-with-scripts.json"));

  fixture->script_loader = unity_webapps_script_loader_new ();
}

static void
teardown_fixture_simple (AvailableApplicationTestFixture *fixture,
                         gconstpointer user_data)
{
  g_object_unref (G_OBJECT (fixture->app));
  g_object_unref (G_OBJECT (fixture->script_loader));
}

static void
test_load_script_with_requires (AvailableApplicationTestFixture *fixture,
                                gconstpointer user_data)
{
  gchar *content =
    unity_webapps_script_loader_get_userscript_contents (
        fixture->script_loader, fixture->app);

  g_assert (0 == g_strcmp0(content,
                           "\n// imported script: common.js"
                           "\nvar f = function (a) {"
                           "\n  console.log('common function');"
                           "\n  return a;"
                           "\n};"
                           "\n"
                           "\nvar test = function () {\n"
                           "};\n"));
}

int 
main (int argc, char **argv)
{
  g_type_init ();
  g_test_init (&argc, &argv, NULL);

  g_setenv("UNITY_WEBAPPS_CONTEXT_USER_DIR", g_get_current_dir(), TRUE);

  unity_webapps_debug_initialize_flags ();

  g_test_add("/Applications/Available/Local/LoadScriptContentWithRequires",
             AvailableApplicationTestFixture,
             NULL,
	     setup_fixture_simple,
             test_load_script_with_requires,
             teardown_fixture_simple);
  
  return g_test_run ();
}
