#include "power.h"
#include "board.h"
#include "rtc.h"
#include "low_Power.h"
#include "led.h"
#include "buttons.h"

#ifdef VBATTPIN
#include "Battery.h"
  Battery battery(VBATTMIN, VBATTMAX, VBATTPIN);
#endif

void initBattery(void)
{
#ifdef VBATTPIN
  battery.begin(VBATTREF, (R12+R13)/R13); //R1 = 220K, R2 = 100K, factor = (R1+R2)/R2
#endif
}

void batterydisplay(void)
{
#ifdef VBATTPIN
  uint16_t currentlevel = battery.level();
 
    if (currentlevel > 90)
    {
      turnOnLed(3);
    }
    if (currentlevel > 50)
    {
      turnOnLed(2);
    }
    if (currentlevel > 20)
    {
      turnOnLed(1);
    }

#endif
}

void batteryCheck(void)
{
#ifdef VBATTPIN
  if (battery.voltage() < VBATTMIN)
  {
    for( int i = 0; i < 10;i++)
    {
      turnOnLed(1);
      delay(300);
      turnOffLed(1);
      delay(300);
    }
    delay(5000);
    shutdown();
  }
#endif
}

//low power
void initLowPower(void)
{
  LowPower_init();
}

void shutdown(void)
{
  LowPower_shutdown();
}

void HandlePower(void)
{
  HandleTimeOut();
  batteryCheck();
}


void HandleTimeOut(void)
{
  uint64_t currentmillis = millis();
  static uint64_t lasttimeOut = 0;
  static bool buttonChanged = false;

  if (!lasttimeOut)
  {
    lasttimeOut = currentmillis;
    buttonChanged = anybutton();
  }

  //check if lastTime is initialized or timeout expired
  if ((currentmillis - lasttimeOut > IDLESHUTDOWN))
  {
    turnOffAllLed();
    shutdown();
  }
  else
  {
    if (buttonChanged != anybutton())
    {
      buttonChanged = anybutton();
      //game in progress, update timer
      lasttimeOut = currentmillis;
    }
  }
}