#include <Arduino.h>
#include "Button.h"

Button::Button(const int outPin, const int inPin, const int redPin, const int orangePin, const int greenPin)
{
  out     = outPin;
  in      = inPin;
  red     = redPin;
  orange  = orangePin;
  green   = greenPin;

  expectedClicks = expectedCPS * time;

  pinMode(in,   INPUT);
  pinMode(out,  OUTPUT);

  pinMode(red,    OUTPUT);
  pinMode(orange, OUTPUT);
  pinMode(green,  OUTPUT);

  digitalWrite(out, HIGH);
  digitalWrite(red, HIGH);
}

bool Button::measure()
{
  //	Evaluate how much time since the last press.
  clicksPerSecond = 1 / ((millis() - timePressed) / 1000);

  //  Calculate performance based on the expected clicks per second we configured.
  int performance = 0;
  
  if (clicksPerSecond > expectedCPS / 2)  performance = 1;
  if (clicksPerSecond > expectedCPS)      performance = 2;

  //  Light the LED's according to the calculated performance.
  if (performance >= 1) digitalWrite(orange, HIGH);
  else                  digitalWrite(orange, LOW);

  if (performance >= 2) digitalWrite(green, HIGH);
  else                  digitalWrite(green, LOW);

  //	Return if the button is not pressed down.
  if (digitalRead(in) == LOW)
  {
    alreadyPressed = false;
    return false;
  }

  //	Return if the button was already pressed the previous iteration.
  if (alreadyPressed) return false;

  //  Print info. Only use for debugging, as this will clutter the serial port!
  /*
  Serial.print("It has been " + String((millis() - timePressed) / 1000) + " seconds since last press.");
  Serial.print("\t");
  Serial.print("Clicks per second is: " + String(clicksPerSecond) + ".");
  Serial.print("\t");
  Serial.print("Performance: " + String(performance) + ".");
  Serial.println();
  */

  //  Send information to the serial port.
  Serial.println("pressed!:");

  //	Save variables for next iteration.
  clicks++;
  timePressed     = millis();
  alreadyPressed  = true;
  
  //  Return true.
  return true;
}