#include "BPMDetect.h"

#include "log.h"

BPMDetect::BPMDetect(int divider):
  m_divider{divider},
  m_count{}
{
}

// Strategy: evaluate last 3 valid beats
// always skip m_divider-1 beats
void BPMDetect::receive_event()
{
  // guard by divider
  ++m_count;
  if (m_count < m_divider) {
    return;
  } else {
    m_count = 0;
  }

  // calculate bpm
  time_point now = clock_type::now();

  m_timestamps.push_back(now);

  while (m_timestamps.size() > 3) {
    m_timestamps.pop_front();
  }

  if (m_timestamps.size() == 3) {
    int bpm = 60 * 2 / std::chrono::duration<double>(m_timestamps.back() - m_timestamps.front()).count();

    signal_bpm(bpm);
  }
}