/*
* tap_bpm.cc
* DIN Is Noise is copyright (c) 2006-2024 Jagannathan Sampath
* DIN Is Noise is released under GNU Public License 2.0
* For more information, please visit https://dinisnoise.org/
*/


#include "tap_bpm.h"
#include "chrono.h"
#include "input.h"

extern ui_clock ui_clk;

tap_display::tap_display (int sz) {
  lmb_clicked = 0;
  set_extents (0, 0, sz, sz);
  tapt = 0;
  startt = flasht = 0;
  flash = 0;
}

void tap_display::set_pos (int x, int y) {
  widget::set_pos (x, y);
  box<int>& e = extents; 
  int dw = 0.4 * e.width, dh = 0.4 * e.height;
  inner (e.midx - dw, e.midy - dh, e.midx + dw, e.midy + dh);
}

int tap_display::handle_input () {
  int r = widget::handle_input ();
  if (hover) {
    if (keypressed (SDLK_RETURN)) calc_bpm ();
    if (lmb) {
      if (lmb_clicked == 0) {
        calc_bpm ();
        lmb_clicked = 1;
      }
    } else lmb_clicked = 0;
  }

  return r;

}

void tap_display::calc_bpm () {
  float now = ui_clk ();
  float dt = now - tapt;
  tapt = ui_clk ();
  if (dt) set_bpm (60.0 / dt);
  flash = 1;
}

void tap_display::set_bpm (float b, int reset) {
  bpm = b;
  float bps = bpm / 60.;
  flasht = 1.0 / bps;
  if (lis) lis->changed (*this);
  if (reset) startt = ui_clk ();
}

void tap_display::draw () {
  widget::draw_bbox ();
  if (flash) {
    glRecti (inner.left, inner.bottom, inner.right, inner.top);
    flash = 0;
  }
}

void tap_display::set_listener (change_listener<tap_display>* l) {
  lis = l;
}
