#include "display.h"

SSD1306Wire display(0x3c, SDA, SCL);

e_displayStates displayState = DISPLAY_INIT;
uint32_t lastDisplayCycle = 0;
uint32_t lastDisplayUpdate = 0;

void drawDSMRstats(void)
{
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(ArialMT_Plain_10);
  display.drawString(0, 0, "DSMR stats:");
  display.drawString(0, 11, getMsgCount());
}

void drawElecFrame(void)
{
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(ArialMT_Plain_10);
  display.drawString(0, 0, "Electricity:");

  display.drawString(0, 11, getElecDelivered());
  display.drawString(0, 22, getElecReturned());
}

void drawGasFrame(void)
{
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.setFont(ArialMT_Plain_10);
  display.drawString(0, 0, getGasDelivered());
}

void drawInitFrame(void)
{
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 12, "DU-DSMR-W");
  display.drawXbm(0, 0, wifiicon10x10_width, wifiicon10x10_height, wifi10x10_png_bits);
  display.drawXbm(16,0, download_cloud_solid_png_width, download_cloud_solid_png_height, download_cloud_solid_png_bits);
}

void initDisplay(void)
{
  display.init();
  drawInitFrame();
  display.display();

  Serial.printf("initdisplay: h=%u, w=%u\n", display.height(), display.width());
}

e_displayStates nextFrame(void)
{
  displayState = static_cast<e_displayStates>(static_cast<int>(displayState) + 1);
  if (displayState == DISPLAU_LAST)
  {
    displayState = DISPLAY_DSMR1;
  }
  return displayState;
}

void handleDisplay(void)
{
  uint32_t timeNow = millis();

  if (timeNow - lastDisplayUpdate > DISPLAY_CYCLE_TIME)
  {
    //lastDisplayUpdate
    display.clear();

    switch (displayState)
    {
    case DISPLAY_INIT:
    {
      drawInitFrame();
    }
    break;
    case DISPLAY_DSMR1:
    {
      drawElecFrame();
    }
    break;
    case DISPLAY_DSMR2:
    {
      drawGasFrame();
    }
    break;
    case DISPLAY_DSMR3:
    {
      drawDSMRstats();
    }
    break;
    default:
    {
      displayState = nextFrame();
    }
    break;
    }
    display.display();
    lastDisplayUpdate = timeNow;
  }

  if (timeNow - lastDisplayCycle > DISPLAY_CYCLE_TIME)
  {
    displayState = nextFrame();
    lastDisplayCycle = timeNow;
  }
}
