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

#include "button.h"
#include "font.h"
#include "chrono.h"
#include "input.h"
#include "log.h"

using std::string;

button::button () {
  lsnr = 0;
  start_time = 0;
  click = 0;
  click_repeat = 0;
  first_repeat_time = 1. / 4;
	subsequent_repeat_time = 1. / 16;
}

void button::draw () { label::draw (); }

int button::handle_input () {
  widget::handle_input ();
  if (lmb) {
    if (hover) {
			widget::focus = this;
      if (click == 0) {
        if (click_repeat) {
          start_time = ui_clk ();
          repeat_time = first_repeat_time;
        }
        click = 1;
        call_listener ();
        return click;
      }
      if (click_repeat) {
        double now = ui_clk ();
        double dt = now - start_time;
        if (dt >= repeat_time) {
          call_listener ();
          repeat_time = subsequent_repeat_time;
          start_time = now;
        }
      }
    }
  } else {
		if (click) {
			click = 0;
			repeat_time = first_repeat_time;
			defocus (this);
		}
  }
  return click;
}


int button::call_listener () {
	if (lsnr) {
		lsnr->clicked (*this);
		return 1;
	}
	return 0;
}
