#include "icons.h"
#include "menu.h"

using namespace menus;

CMCMenu::CMCMenu(lib::Display& display, lib::Flash& flash, uint8_t color) :
  Menu(display, flash),
  color(color),
  current(2),
  previous(1),
  progress(0.7f)
{
  display.clear();
}

void CMCMenu::onTick(float dt)
{
  constexpr float CENTER_X = 120;
  constexpr float CENTER_Y = 160;
  constexpr float DT_SCALE = 1.4f;
  constexpr uint8_t STEP = 48;

  old_progress = progress;

  if (progress < 1.0f)
  {
    progress += dt * DT_SCALE;
    if (progress >= 0.75f)
    {
      progress = 1.0f;
    }

    for (int8_t dcmc = -1; dcmc <= 1; dcmc++)
    {
      const int8_t dir = (previous > current ? 1 : -1);
      const int8_t cmc_to_draw = current + dir * dcmc;

      if (cmc_to_draw < 0 || cmc_to_draw > 20)
      {
        continue;
      }

      const float offset
        = dir * ease::outElastic(progress) * STEP + (dir * (dcmc - 1)) * STEP;
      const float old_offset = dir * ease::outElastic(old_progress) * STEP
                               + (dir * (dcmc - 1)) * STEP;

      // erase old
      display->fill(CENTER_X - 15 + old_offset, CENTER_Y - 15, 32, 32, 0, 0,
                    0);

      // draw new
      display->fill(CENTER_X - 15 + offset, CENTER_Y - 15, 32, 32,
                    icon::NUMBER_ICONS[cmc_to_draw]);
    }
  }
}
void CMCMenu::onResume() {}

void CMCMenu::onLeftPressed()
{
  if (progress >= 1 && current > 0)
  {
    previous = current;
    current -= 1;

    progress = 0;
  }
}
void CMCMenu::onLeftHeld() {}

void CMCMenu::onMenuPressed()
{
  push_menu<SelectMenu>(*display, *flash, color, current);
}
void CMCMenu::onMenuHeld() {}

void CMCMenu::onRightPressed()
{
  if (progress >= 1 && current < 20)
  {
    previous = current;
    current += 1;

    progress = 0;
  }
}
void CMCMenu::onRightHeld() {}
