//
// Created by rhetenor on 21.09.18.
//

#include "DistributingEvent.h"

namespace flippR_driver
{
namespace input
{

DistributingEvent::DistributingEvent(uint8_t address, int priority, std::string name,
                                     std::chrono::milliseconds bounce_time, std::shared_ptr<EventNotifier> event_notifier)
:
  Event(address, priority, std::move(name)),
  bounce_time(bounce_time),
  event_notifier(std::move(event_notifier)),
  activation_state(NOT_ACTIVATED)
{}

void DistributingEvent::distribute()
{
  event_notifier->distribute_event(*this);
}

void DistributingEvent::active()
{
  if(!is_bouncing())
  {
    if(activation_state != ACTIVATED)
    {
      activation_state = activation_state == NOT_ACTIVATED ? FIRST_ACTIVATED : ACTIVATED;
    }

    last_activation = std::chrono::high_resolution_clock::now();

    if(activation_state == FIRST_ACTIVATED)
    {
      this->distribute();
    }
  }
}

bool DistributingEvent::is_bouncing()
{
  std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
  std::chrono::milliseconds elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_activation);

  return elapsed_time < bounce_time;
}

void DistributingEvent::inactive()
{
  if(activation_state == ACTIVATED)
  {
    this->last_activation = std::chrono::high_resolution_clock::now();
    activation_state = NOT_ACTIVATED;
  }
}

}
}