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

namespace
{

constexpr uint8_t ERASE_DATA[icon::TEXT_ICON_LENGTH] = {};

}

using namespace menus;

SelectMenu::SelectMenu(lib::Display& display, lib::Flash& flash, uint8_t color,
                       uint8_t cmc) :
  Menu(display, flash),
  color(color),
  cmc(cmc),
  current(0),
  found(0)
{
  for (int i = 0; i < CardSlot::MAX_CARDS; i++)
  {
    CardSlot slot(flash, i);
    if (slot.is_used() && slot.get_cmc() == cmc
        && (slot.get_colors() == color || (slot.get_colors() & color)))
    {
      filtered[found++] = i;
    }
  }

  if (found > 0)
  {
    draw();
  }
}

void SelectMenu::onTick(float dt)
{
  if (found == 0)
  {
    pop_menu(2);
  }
}
void SelectMenu::onResume() { draw(); }

void SelectMenu::onLeftPressed()
{
  if (current > 0)
  {
    draw_letter(1, current + 1, 0xFF);

    current -= 1;

    draw_letter(1, current + 1, 'x' - 'a');
  }
}
void SelectMenu::onLeftHeld() {}

void SelectMenu::onMenuPressed()
{
  push_menu<CardMenu>(*display, *flash, filtered[current]);
}
void SelectMenu::onMenuHeld() {}

void SelectMenu::onRightPressed()
{
  if (current < found - 1)
  {
    draw_letter(1, current + 1, 0xFF);

    current += 1;

    draw_letter(1, current + 1, 'x' - 'a');
  }
}
void SelectMenu::onRightHeld() {}

void SelectMenu::draw()
{
  display->clear();

  for (int i = 0; i < found; i++)
  {
    if (i == current)
    {
      draw_letter(1, i + 1, 'x' - 'a');
    }

    CardSlot slot(*flash, filtered[i]);
    for (int n = 0; n < slot.get_name_length(); n++)
    {
      draw_letter(n + 3, i + 1, slot.get_name()[n] - 'a');
    }
  }
}

void SelectMenu::draw_letter(uint8_t x, uint8_t y, uint8_t letter)
{
  if (x >= 20)
  {
    return;
  }

  if (letter >= 26)
  {

    display->fill(x * 12, y * 19, 12, 19, 0, 0, 0);
  }
  else
  {
    display->fill(x * 12, y * 19, 12, 19, icon::LETTERS[letter]);
  }
}
