
#include "Controller.h"

//********************************************************************

// potentiometer generic constructor
//********************************************************************
Pot::Pot(byte pin, byte control, byte channel, byte sensitivity, bool canMutate)
{
  _pin = pin;
  potValue = analogRead(_pin)/8;
  _oldValue = potValue;
  potControl = control;
  potChannel = channel;
  _sensitivity= sensitivity;
  mutante = canMutate;
}

//updating the potentiometer
void Pot::updatePot(){
  potValue = analogRead(_pin)/8;
}

//method for return if we need to send midi message
bool Pot::checkPot(){
  if(potValue + _sensitivity < _oldValue || potValue - _sensitivity > _oldValue){
    _oldValue = potValue;
    return true;
  }
  return false;
}

//mehotd for change values of pot, needed ?
void Pot::newValue(byte value, byte channel) {
  potControl = value;
  potChannel = channel;
}
//********************************************************************


// button generic constructor
//********************************************************************

//Button (Pin Number, Command, Note Number, Channel, Debounce Time)
Button::Button(byte pin, byte command, byte value, byte channel, byte debounce, bool canMutate)
{
  _pin = pin;
  pinMode(_pin, INPUT_PULLUP);
  _value = value;
  _command = command;
  _debounce = debounce;
  _time = 0;
  _busy = false;
  _status = 0b00000010;
  _last = 1;
  Bcommand = command;
  Bvalue = value;
  Bchannel = channel;
  Btoggle = 0;
  mutante = canMutate;
}


byte Button::getValue()
{
  // If BUSY bit not set - read button
  if (bitRead(_status, 0) == false) { // If busy false
    if (digitalRead(_pin) == _last) return 2; // If same as last state - exit
  }

  // If NEW Bit set - Key just pressed, record time
  if (bitRead(_status, 1) == true) { // If new is true
    bitSet(_status, 0); // Set busy TRUE
    bitClear(_status, 1); // Set New FALSE
    _time = millis();
    return 255;
  }

  // Check if debounce time has passed - If no, exit
  if (millis() - _time < _debounce) return 255;

  // Debounce time has passed. Read pin to see if still set the same
  // If it has changed back - assume false alarm
  if (digitalRead(_pin) == _last) {
    bitClear(_status, 0); // Set busy false
    bitSet(_status, 1); // Set new true
    return 255;
  }

  // If this point is reached, event is valid. return event type
  else {
    bitClear(_status, 0); // Set busy false
    bitSet(_status, 1); // Set new true
    _last = ((~_last) & 0b00000001); // invert _last
    return _last;
  }
}

void Button::newValue(byte command, byte value, byte channel)
{
  Bvalue = value;
  Bcommand = command;
  Bchannel = channel;
}
