#include "apt-cache-generator.h"
#include "apt-cache-generator-entry.h"
#include <stdarg.h>

struct _AptCacheGenerator {
  GList *entries;
};

AptCacheGenerator *
apt_cache_generator_new ()
{
  AptCacheGenerator *generator;
  
  generator = g_new0(AptCacheGenerator, 1);
  
  generator->entries = NULL;
  
  return generator;
}

static void
apt_cache_generator_free_entries (AptCacheGenerator *generator)
{
  GList *w;
  
  for (w = generator->entries; w != NULL; w = w->next)
    {
      AptCacheGeneratorEntry *entry;
      
      entry = (AptCacheGeneratorEntry *)w->data;
      
      apt_cache_generator_entry_free (entry);
    }
  
  g_list_free (generator->entries);
}

void
apt_cache_generator_free (AptCacheGenerator *generator)
{
  apt_cache_generator_free_entries (generator);
  g_free (generator);
}

gchar *
apt_cache_generator_get_available (AptCacheGenerator *generator)
{
  GString *available;
  GList *w;
  gchar *ret;
  
  available = g_string_new ("");
  for (w = generator->entries; w != NULL; w = w->next)
    {
      AptCacheGeneratorEntry *entry;
      gchar *entry_serialized;
      
      entry = (AptCacheGeneratorEntry *)w->data;
      entry_serialized = apt_cache_generator_entry_serialize (entry);
      
      g_string_append_printf (available, "%s\n", entry_serialized);
    }
  
  ret = available->str;
  g_string_free (available, FALSE);
  return ret;
}

static AptCacheGeneratorEntry *
apt_cache_generator_construct_application (AptCacheGenerator *generator, const gchar *name)
{
  AptCacheGeneratorEntry *entry;
  
  entry = apt_cache_generator_entry_new (name, "1.0");
  
  return entry;
}

void 
apt_cache_generator_add_application (AptCacheGenerator *generator, const gchar *name)
{
  AptCacheGeneratorEntry *entry;

  entry = apt_cache_generator_construct_application (generator, name);
  generator->entries = g_list_append (generator->entries, entry);
}

void
apt_cache_generator_add_webapp (AptCacheGenerator *generator, const gchar *name, const gchar *webapp_name, const gchar *webapp_domain, .../*Includes*/)
{
  AptCacheGeneratorEntry *entry;
  const gchar *include;
  va_list argp;
  
  entry = apt_cache_generator_entry_new (name, "1.0");
  apt_cache_generator_entry_set_webapp_name (entry, webapp_name);
  apt_cache_generator_entry_set_webapp_domain (entry, webapp_domain);
  
  va_start (argp, webapp_domain);
  
  include = va_arg (argp, gchar *);
  while (include != NULL)
    {
      apt_cache_generator_entry_add_webapp_include (entry, include);
      include = va_arg (argp, gchar *);
    }
  
  va_end (argp);
  
  // TODO: Factor out
  generator->entries = g_list_append (generator->entries, entry);
}
