#include "interpreter.hpp"
#include "sound.hpp"
#include "playlist.hpp"

#include "xm_player/xm.h"
#include "xm_player/cover.hpp"

#include "xm/CloudsAhead.xm.h"
#include "xm/CottageFantasy.xm.h"
#include "xm/RedBlossom.xm.h"
#include "xm/TheClockOfElery.xm.h"
#include "xm/ForestAtTwilight.xm.h"
#include "xm/SpringWaltz.xm.h"
#include "xm/TheMountainsOfElmindeer.xm.h"

#include "platform/texture.hpp"

namespace playlist {

  struct state state = {
    .playlist_ix = -1,
    .loops = -1,
  };

  const playlist_item playlist[] = {
    {
      .artist = "Shiroiii",
      .title = "Clouds Ahead",
      .start = (int)&_binary_xm_CloudsAhead_xm_start,
      .cover_ix = texture::offset::thebeach,
    },
    {
      .artist = "Shiroiii",
      .title = "Cottage Fantasy",
      .start = (int)&_binary_xm_CottageFantasy_xm_start,
      .cover_ix = texture::offset::mossycottage,
    },
    {
      .artist = "Shiroiii",
      .title = "Red Blossom",
      .start = (int)&_binary_xm_RedBlossom_xm_start,
      .cover_ix = texture::offset::redtree,
    },
    {
      .artist = "Shiroiii",
      .title = "The Clock Of Elery",
      .start = (int)&_binary_xm_TheClockOfElery_xm_start,
      .cover_ix = texture::offset::clocks,
    },
    {
      .artist = "Shiroiii",
      .title = "Forest At Twilight",
      .start = (int)&_binary_xm_ForestAtTwilight_xm_start,
      .cover_ix = texture::offset::silvertrees,
    },
    {
      .artist = "Shiroiii",
      .title = "Spring Waltz",
      .start = (int)&_binary_xm_SpringWaltz_xm_start,
      .cover_ix = texture::offset::tree,
    },
    {
      .artist = "Shiroiii",
      .title = "Mountains of Elmindeer",
      .start = (int)&_binary_xm_TheMountainsOfElmindeer_xm_start,
      .cover_ix = texture::offset::mountain,
    },
  };

  const int playlist_length = (sizeof (playlist)) / (sizeof (playlist[0]));

  bool next(bool stop_sound)
  {
    if (state.loops < 0 || state.loops >= 1) {
      state.playlist_ix += 1;
      state.loops = 0;

      if (state.playlist_ix >= playlist_length)
        state.playlist_ix = 0;

      printf("next deferred_load playlist_ix %d\n", state.playlist_ix);
      interpreter::stop_sound();

      const playlist_item& item = playlist[state.playlist_ix];
      interpreter::deferred_load(item.start, item.cover_ix);
      return true;
    } else {
      state.loops += 1;
      interpreter::state.pattern_order_table_index = 0;
      return false;
    }
  }

  bool prev(bool stop_sound)
  {
    state.playlist_ix -= 1;
    if (state.playlist_ix < 0)
      state.playlist_ix = playlist_length - 1;

    printf("prev deferred_load playlist_ix %d\n", state.playlist_ix);
    interpreter::stop_sound();
    const playlist_item& item = playlist[state.playlist_ix];
    interpreter::deferred_load(item.start, item.cover_ix);

    return true;
  }
}
