#include "EventHandler.h"

EventHandler::EventHandler(uint8_t queueSize) : _maxQueueSize(queueSize)
{
  //We set the various inputs needed
  pinMode(GPIO_0, INPUT);
}

void EventHandler::run()
{
  //FLASH_BUTTON PART
  if(!digitalRead(GPIO_0) && !_flashBtnPushed && millis() - _flashBtnDebounceTs > 200)
  {
    _flashBtnPushed = true;
    _flashBtnTs = millis();
  }

  if(!digitalRead(GPIO_0) && _flashBtnPushed && millis() - _flashBtnTs > 500 && !_flashBtnLongPressFired)
  {
    _flashBtnLongPressFired = true;
    addEventCheckSizeLimit(FLASH_BUTTON_LONG_PRESS);
  }

  if(digitalRead(GPIO_0) && _flashBtnPushed && millis() - _flashBtnTs < 500)
  {
    _flashBtnPushed = false;
    addEventCheckSizeLimit(FLASH_BUTTON_PRESS);
    _flashBtnDebounceTs = millis();
  }
  else if(digitalRead(GPIO_0) && _flashBtnPushed && _flashBtnLongPressFired)
  {
    _flashBtnPushed = false;
    _flashBtnLongPressFired = false;
    _flashBtnDebounceTs = millis();
  }
  //FLASH_BUTTON END PART
}

EventHandler::Event EventHandler::getEvent()
{
  if(_eventQueue.count() > 0)
    return _eventQueue.remove();

  return NO_EVENT;
}

void EventHandler::addEventCheckSizeLimit(Event e)
{
  if(_eventQueue.count() < _maxQueueSize)
  {
    _eventQueue.add(e);
  }
  else
  {
    delete _eventQueue.removeRef();
    _eventQueue.add(e);
  }
}
