
#include <stdlib.h>

#include "../mecha/mecha.h"

#include "playlist.h"
#include "file_entry.h"

#include "order_playlist_engine.h"

static FileEntry * order_playlist_engine_get_next (playlist *p);
static int order_playlist_engine_add_file (playlist *p, FileEntry *file);

playlist_engine *
order_playlist_engine_init (void)
{
   playlist_engine *p;

   p = (playlist_engine *) malloc (sizeof (playlist_engine));

   p->name = strFcopy ("order");
   p->type = PLAYLIST_TYPE_ORDER;
   p->get_next = order_playlist_engine_get_next;
   p->add_file = order_playlist_engine_add_file;

   return (p);
}

static FileEntry *
order_playlist_engine_get_next (playlist *p)
{
   if (p->type != PLAYLIST_TYPE_ORDER)
      return (0);

   if (lstFlist_size (p->filelist) == 0)
      return (0);

   if (p->len == 0)
   {
      lstTlist_elem *ep;
      int i;

      p->len = lstFlist_size (p->filelist);

      p->list = (FileEntry **) malloc (sizeof (FileEntry *) * p->len);

      for (ep = lstFlist_head (p->filelist), i = 0; ep; ep = lstFlist_next (ep))
         p->list[i++] = lstFlist_data (ep);

      p->offset = 0;
   }

   if (p->offset >= p->len)
      p->offset = 0;

   return (file_entry_duplicate (p->list[p->offset++]));
}


static int
order_playlist_engine_add_file (playlist *p, FileEntry *entry)
{
   if (p->len > 0)
   {
      p->list = realloc (p->list, sizeof (FileEntry *) * (p->len + 1));
      p->list[p->len] = entry;
      p->len++;
   }

   lstFlist_add_next (p->filelist, lstFlist_tail (p->filelist), entry);

   return (0);
}
