#include "./move.h"
#include "./home.h"
#include "include/config.h"
#include "include/metrics.h"
#include "lib/settings.h"
#include "lib/control.h"
#include "lib/state.h"


void MoveScreen::onShow()
{
  auto startY = Metrics::LargeTextLineHeight;
  auto arrowY = startY + Metrics::LargeTextLineHeight + Metrics::LargeTextLineVArrowYOffset;
  auto arrowX = (Config::DisplayWidth - Metrics::VArrowWidth) / 2;
  auto stopY = Config::DisplayHeight - Metrics::LargeTextLineHeight;

  this->display->fillScreen(Config::ColorMoveBackground);

  // Stop
  this->display->setFont(Metrics::SmallFont);
  this->display->setTextSize(Metrics::SmallFontTextSize);

  this->display->setTextColor(Config::ColorMoveStop);
  this->printCentered("Press any button to", stopY - Metrics::SmallTextLineHeight);

  this->display->setFont(Metrics::LargeFont);
  this->display->setTextSize(Metrics::LargeFontTextSize);

  this->printCentered("STOP", stopY + Metrics::LargeTextLineYOffset);

  char targetHeightText[6];
  Control.getDisplayHeight(&targetHeightText[0], Control.getMoveTarget());
  this->display->setTextColor(Config::ColorMoveCurrent);

  // Target and arrow
  if (Control.getMoveDirection() == MoveDirection::Up)
  {
    this->currentHeightY = startY + (Metrics::LargeTextLineHeight * 2);

    this->printCentered(&targetHeightText[0], startY + Metrics::LargeTextLineYOffset);
    this->drawArrowUp(arrowX, arrowY, Config::ColorMoveArrow);
  }
  else
  {
    this->currentHeightY = startY;

    this->printCentered(&targetHeightText[0], startY + (Metrics::LargeTextLineHeight * 2) + Metrics::LargeTextLineYOffset);
    this->drawArrowDown(arrowX, arrowY, Config::ColorMoveArrow);
  }

  this->lastRefresh = CurrentTime;
  this->drawCurrentHeight();
}


void MoveScreen::onButton(Button button)
{
  Control.moveStop();
  this->screenManager->show<HomeScreen>();
}


void MoveScreen::onTick()
{
  bool isStabilizing = Control.getIsStabilizing();

  // Don't update every tick, monitoring the current height is more
  // important and the flicker would be unpleasant as well.
  if (this->lastIsStabilizing != isStabilizing || CurrentTime - this->lastRefresh >= Config::DisplayRefreshRate)
  {
    this->drawCurrentHeight();
    this->lastRefresh = CurrentTime;
    this->lastIsStabilizing = isStabilizing;
  }
}


void MoveScreen::drawCurrentHeight()
{
  char currentHeightText[6];

  if (Control.getIsStabilizing())
    Control.getDisplayHeight(&currentHeightText[0], 0);
  else
    Control.getDisplayHeight(&currentHeightText[0], Control.getCurrentHeight());

  if (this->lastTextWidth > 0)
    this->display->fillRect((Config::DisplayWidth - this->lastTextWidth) / 2, this->currentHeightY, this->lastTextWidth, Metrics::LargeTextLineHeight, Config::ColorMoveBackground);

  this->display->setTextColor(Config::ColorMoveTarget);
  this->lastTextWidth = this->printCentered(&currentHeightText[0], this->currentHeightY + Metrics::LargeTextLineYOffset);
}