#include <Arduino.h>
#include "vinka_key.h"
#include <Wire.h>

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

#define address 0x65
byte error;
int LONG_CLICK_DELAY = 500;
int DEBOUNCING_DELAY = 300;
int lastButtonId = -1;
unsigned long lastClick = 0;
unsigned long lastRawPressed = 0;

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

void setupButtons()
{
  //Wire.beginTransmission(address);
  error = Wire.requestFrom(address, 2);
  //error = Wire.endTransmission();
  if (error != 0){
    Serial.println("vinka_keyboard not found, check wiring?");
    while (1);
  }
  Serial.println("vinka keyboard found!");
}




int getPressedButton() {

int b = -1;
unsigned char temp[2];
Wire.requestFrom(address, 2);
for(unsigned char i = 0; Wire.available() > 0; i++)
  {
    temp[i] = Wire.read();
  }   
 /* if((temp[0]>0)|(temp[1]>0)){
  if(temp[0]&0b00000001) Serial.print("1");
  if(temp[0]&0b00000010) Serial.print("4");
  if(temp[0]&0b00000100) Serial.print("7");
  if(temp[0]&0b00001000) Serial.print("*");
  if(temp[0]&0b00010000) Serial.print("2");
  if(temp[0]&0b00100000) Serial.print("5");
  if(temp[0]&0b01000000) Serial.print("8");
  if(temp[0]&0b10000000) Serial.print("0");
  if(temp[1]&0b00000001) Serial.print("3");
  if(temp[1]&0b00000010) Serial.print("6");
  if(temp[1]&0b00000100) Serial.print("9");
  if(temp[1]&0b00001000) Serial.print("#");
  if(temp[1]&0b00010000) Serial.print("A");
  if(temp[1]&0b00100000) Serial.print("B");
  if(temp[1]&0b01000000) Serial.print("C");
  if(temp[1]&0b10000000) Serial.print("D");
  Serial.println(" ");
  }
 *///// Get the currently touched pads
  
for (uint8_t i=0; i <2; i++){
  for (int8_t j=0; j<8; j++){
    if(temp[i] & _BV(j)){
      b= 8*i + j;
      lastRawPressed = millis();
      break;
    }
  if (b>=0) break ;
  }
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 + 16;
            lastClick = currentClick;
            } else {
               b = -1;
            }
          }
  } else {
    if (millis() - lastRawPressed > 100) {
       lastButtonId = -1;
    }
  }
  return b;
}
