#include <stdint.h>
#include <stdlib.h>
#include <util/delay.h>
#include <ssd1306xled.h>
#include "power.h"
#include "buttons.h"
#include "screen/counter.h"


// Forward declarations
uint8_t handleGlobalInput();
void handleCurrentScreen();



int main()
{
  // Delay is required on power-on for the SSD1306 to initialize,
  _delay_ms(40);
  ssd1306_init();
  ssd1306_clear();

  buttons_init();

  while (1)
  {
    checkPower();
    if (!handleGlobalInput())
    {
      if (powerState == On)
      {
          handleCurrentScreen();

          if (!buttons_active())
            sleepUntilButton(_BV(BUTTON_UP) | _BV(BUTTON_DOWN) | _BV(BUTTON_OPTION));
      }
    }
  }

  return 0;
}


uint8_t handleGlobalInput()
{
  if (button_is_pressed_short(&buttonOption))
  {
    // Turn off power to the screen
    if (powerState == On)
      setPowerState(ManualOff);

    return 1;
  }

  return 0;
}


void handleCurrentScreen()
{
  handleCounterScreen();
}