#include "NerfStatTrakConfig.h"
#include "Globals.h"
#include "StateHandler.h"
#include "LowPower.h"


SegmentDisplay* display;
Button* buttonA;
Button* buttonB;
Button* buttonArmed;

uint32_t shots = 0;
uint32_t hits = 0;

unsigned long currentTime;
AbstractStateHandler* currentState;


void setCurrentState(AbstractStateHandler* value)
{
  buttonA->block();
  buttonB->block();

  currentState = value;
  currentState->setup();
}


void update()
{
  currentTime = millis();

  buttonA->update(currentTime);
  buttonB->update(currentTime);
  buttonArmed->update(currentTime);

  // Count the shot no matter which state we're in
  if (buttonArmed->changed() && !buttonArmed->pressed())
    shots++;
}


void wakeUp()
{
}


void sleep()
{
  display->clear();

  // Uses RocketScream's Low-Power library
  // https://github.com/rocketscream/Low-Power
  uint32_t interrupt = digitalPinToInterrupt(NerfButtonWakeUp);

  attachInterrupt(interrupt, wakeUp, NerfButtonWakeUpState);
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
  detachInterrupt(interrupt);


  currentTime = millis();

  // The button triggers the wake-up, so block the first release after
  if (NerfButtonWakeUp == NerfButtonA)
  {
    buttonA->update(currentTime);
    buttonA->block();
  }

  if (NerfButtonWakeUp == NerfButtonB)
  {
    buttonB->update(currentTime);
    buttonB->block();
  }
}