#include "button.hpp"

#include <Arduino.h>

#include "global.hpp"

void Button::setup(void) { pinMode(_pin, INPUT_PULLUP); }

bool Button::is_pressed(void) { return digitalRead(_pin) == 0; }

void AnalogButton::setup(void) {
  if (_vRef < 0) {
    calibrate();
  }
}

bool AnalogButton::is_button_pressed(void) { return analogRead(_pin) < _vRef; }

void AnalogButton::calibrate(void) {
  int highRef, lowRef;

#if defined(__BUILD_DEBUG__)
  debugSerial.println(__func__);
  debugSerial.println("Getting high ref > 1000");
#endif /* defined(__BUILD_DEBUG__) */

  /* Get the button released (High) state voltage, should be close to 1024 (analogRead max) */
  do {
    highRef = analogRead(_pin);
    delay(300);
  } while (highRef < 1000);

#if defined(__BUILD_DEBUG__)
  debugSerial.print("highRef=");
  debugSerial.println(highRef);
  debugSerial.print("Getting low ref < ");
  debugSerial.println(highRef - 50);
#endif /* defined(__BUILD_DEBUG__) */

  /* Get the button pushed (Low) state voltage (min of ~5% difference needed to avoid false detection) */
  do {
    lowRef = analogRead(_pin);
    delay(300);
  } while (lowRef > highRef -  50);

#if defined(__BUILD_DEBUG__)
  debugSerial.println("lowRef=");
  debugSerial.println(lowRef);
#endif /* defined(__BUILD_DEBUG__) */

  /* Add ~1% tolerance */
  _vRef = lowRef + 10;
#if defined(__BUILD_DEBUG__)
  debugSerial.println("vRef=");
  debugSerial.println(_vRef);
#endif /* defined(__BUILD_DEBUG__) */
}
