#include "aica/aica.hpp"
#include "../../sound.hpp"
#include "scene/logo/sound.hpp"
#include "pcm/jingle.adpcm.h"

#include "printf/printf.h"

namespace scene::logo::sound {

  const static void * start = reinterpret_cast<void *>(&_binary_pcm_jingle_adpcm_start);
  const static int size = reinterpret_cast<int>(&_binary_pcm_jingle_adpcm_size);
  const static int sample_count = size * 2;
  const static int loop_length = 65528;
  const static int segment_count = sample_count / loop_length;

  void init()
  {
    printf("init\n");
    ::sound::transfer(start, size);

    wait(); aica_sound.common.afsel_mslc_mobuf
      = aica::afsel_mslc_mobuf::AFSEL(0)
      | aica::afsel_mslc_mobuf::MSLC(0);

    wait(); aica_sound.channel[0].LPCTL(1);
    wait(); aica_sound.channel[0].PCMS(2); // adpcm
    wait(); aica_sound.channel[0].LSA(0);
    wait(); aica_sound.channel[0].LEA(loop_length);
    wait(); aica_sound.channel[0].D2R(0x0);
    wait(); aica_sound.channel[0].D1R(0x0);
    wait(); aica_sound.channel[0].RR(0x1f);
    wait(); aica_sound.channel[0].AR(0x1f);

    wait(); aica_sound.channel[0].OCT(0);
    wait(); aica_sound.channel[0].FNS(0);
    wait(); aica_sound.channel[0].DISDL(0xf);
    wait(); aica_sound.channel[0].DIPAN(0x0);

    wait(); aica_sound.channel[0].KYONB(0);
    wait(); aica_sound.channel[0].KYONEX(1);
  }

  void interrupt()
  {
    static int segment = 0;

    wait();
    int lp_sgc_eg = aica_sound.common.lp_sgc_eg;

    if (aica::lp_sgc_eg::SGC(lp_sgc_eg) == 3) { // release
      if (segment != 0)
        return;
      printf("start\n");
      wait(); aica_sound.channel[0].SA(0);
      wait(); aica_sound.channel[0].KYONB(1);
      wait(); aica_sound.channel[0].KYONEX(1);
      return;
    }

    if (aica::lp_sgc_eg::LP(lp_sgc_eg)) {
      segment += 1;
      if (segment >= segment_count) {
        wait(); aica_sound.channel[0].KYONB(0);
        wait(); aica_sound.channel[0].KYONEX(1);
        return;
      }

      printf("loop %d\n", segment);
      int sa = 0 + (loop_length / 2) * segment;
      wait(); aica_sound.channel[0].SA(sa);
    }
  }

}
