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


void MoveSensorErrorScreen::onShow()
{
  auto y = Metrics::LargeTextLineHeight + Metrics::LargeTextLineYOffset;

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


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

  this->display->setTextColor(Config::ColorErrorText);
  this->printCentered("ERROR", y);
  y += Metrics::LargeTextLineHeight;

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

  this->printCentered("height sensor failed", y);
  y += Metrics::SmallTextLineHeight;

  this->printCentered("waiting for stable value", y);
  y += Metrics::SmallTextLineHeight + Metrics::LargeTextLineHeight;

  this->currentHeightY = y;


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

  this->lastRefresh = CurrentTime;
  this->drawLastMeasurement();

  Control.stabilizeStart();
}


void MoveSensorErrorScreen::onButton(Button button)
{
}


void MoveSensorErrorScreen::onTick()
{
  if (Control.stabilized())
  {
    this->screenManager->show<HomeScreen>();
    return;
  }

  if (CurrentTime - this->lastRefresh >= Config::DisplayRefreshRate)
  {
    this->drawLastMeasurement();
    this->lastRefresh = CurrentTime;
  }
}


void MoveSensorErrorScreen::drawLastMeasurement()
{
  char currentHeightText[6];
  Control.getDisplayHeight(&currentHeightText[0], Control.getLastMeasurement());

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

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