#include <Arduino.h>
#include "my_buttons.h"
#include "Adafruit_MPR121.h"

#ifndef _BV
#define _BV(bit) (1 << (bit)) 
#endif

int LONG_CLICK_DELAY = 500;
int DEBOUNCING_DELAY = 300;
int lastButtonId = -1;
unsigned long lastClick = 0;
unsigned long lastRawPressed = 0;

Adafruit_MPR121 cap = Adafruit_MPR121();
// Keeps track of the last pins touched
// so we know when buttons are 'released'
uint16_t lasttouched = 0;
uint16_t currtouched = 0;

void setupButtons()
{
if (!cap.begin(0x5A)) {
    Serial.println("MPR121 not found, check wiring?");
    while (1);
  }
  Serial.println("MPR121 found!");
  cap.setThresholds (8,4);
}




int getPressedButton() {

int b = -1;
// Get the currently touched pads
  currtouched = cap.touched();
  
  for (uint8_t i=0; i<12; i++) {
    // it if *is* touched
    if (currtouched & _BV(i)){
      b = i;
      lastRawPressed = millis();
    }
    if (b>= 0) break ;
  }

  if (b >= 0){
        
          unsigned long currentClick = millis();
          if (lastButtonId != b) {
            if (currentClick > lastClick + DEBOUNCING_DELAY) {
              Serial.println(" Sort");
              lastClick = currentClick;
              tone(BUZZ, 1000, 50);
              lastButtonId = b;
            } else {
              b = -1;
            }
          } else {
            if (currentClick > lastClick + LONG_CLICK_DELAY) {
              Serial.println(" Long");
              lastButtonId = b;
              b = b + 12;
              lastClick = currentClick;
            } else {
              b = -1;
            }
          }
  } else {
    if (millis() - lastRawPressed > 100) {
      lastButtonId = -1;
    }
  }
  return b;
}

