#include "webapp-info.h"
#include <string.h>

struct _WebappInfo {
  gchar *package_name;
  gchar *application_name;
  gchar *domain;

  GPtrArray *urls;
};

WebappInfo *
webapp_info_new (const gchar *package_name)
{
  WebappInfo *info;
  
  info = g_malloc0(sizeof (WebappInfo));
  info->package_name = g_strdup (package_name);
  info->urls = g_ptr_array_new_full (3, g_free);
  
  info->domain = NULL;
  info->application_name = NULL;
  
  return info;
}

void
webapp_info_free (WebappInfo *info)
{
  g_ptr_array_free (info->urls, TRUE);
  g_free (info->package_name);
  g_free (info->application_name);
  g_free (info->domain);

  g_free (info);
}

const gchar *
webapp_info_get_package_name (WebappInfo *info)
{
  return info->package_name;
}

const gchar *
webapp_info_get_application_name (WebappInfo *info)
{
  return info->application_name;
}

void
webapp_info_set_application_name (WebappInfo *info, const gchar *application_name)
{
  g_return_if_fail (info->application_name == NULL);
  
  info->application_name = g_strdup (application_name);
}

const gchar *
webapp_info_get_application_domain (WebappInfo *info)
{
  return info->domain;
}

void
webapp_info_set_application_domain (WebappInfo *info, const gchar *application_domain)
{
  g_return_if_fail (info->domain == NULL);
  
  info->domain = g_strdup (application_domain);
}

void
webapp_info_add_url (WebappInfo *info, const gchar *url)
{
  g_ptr_array_add (info->urls, g_strdup (url));
}

GPtrArray *
webapp_info_get_urls (WebappInfo *info)
{
  return info->urls;
}

gboolean
webapp_info_has_urls (WebappInfo *info)
{
  return (info->urls->len != 0);
}

gboolean
webapp_info_verify (WebappInfo *info)
{
  if (info->package_name == NULL)
    {
      return FALSE;
    }
  if (g_str_has_prefix (info->package_name, "unity-webapps") == FALSE)
    {
      return FALSE;
    }
  if (info->application_name == NULL)
    {
      return FALSE;
    }
  if (strlen (info->application_name) == 0)
    {
      return FALSE;
    }
  if (info->domain == NULL)
    {
      return FALSE;
    }
  if (strlen (info->domain) == 0)
    {
      return FALSE;
    }
  if (webapp_info_has_urls (info) == FALSE)
    {
      return FALSE;
    }
  return TRUE;
}

GVariant *
webapp_info_serialize (WebappInfo *info)
{
  GVariantBuilder b;
  int i;
  
  g_variant_builder_init (&b, G_VARIANT_TYPE("(ssa(s))"));
  
  g_variant_builder_add (&b, "s", info->package_name);
  g_variant_builder_add (&b, "s", info->application_name);
  
  g_variant_builder_open (&b, G_VARIANT_TYPE ("a(s)"));
  
  for (i = 0; i < info->urls->len; i++)
    {
      gchar *url;
      
      url = (gchar *)g_ptr_array_index (info->urls, i);
      g_variant_builder_add (&b, "(s)", url);
    }
  
  g_variant_builder_close (&b);
  
  return g_variant_builder_end (&b);
}
