
#define JOYSTICK_DEBOUNCETIME 50
#define JOYSTICK_AMOUNT 5

#define JOYSTICK_UP_PIN 8
#define JOYSTICK_CENTER_PIN 7
#define JOYSTICK_LEFT_PIN 6
#define JOYSTICK_DOWN_PIN 5
#define JOYSTICK_RIGHT_PIN 4

#define JOYSTICK_UP 1
#define JOYSTICK_CENTER 2
#define JOYSTICK_LEFT 3
#define JOYSTICK_DOWN 4
#define JOYSTICK_RIGHT 5

typedef struct {
  const uint8_t code;
  const uint8_t pin;

  uint16_t pressedTime;
  bool isPressed;//If button pressing - true, else - false
  bool isPressChecked;
} Button;

Button buttons[JOYSTICK_AMOUNT] = {
  {JOYSTICK_UP,     JOYSTICK_UP_PIN, 0, false, false},
  {JOYSTICK_CENTER, JOYSTICK_CENTER_PIN, 0, false, false},
  {JOYSTICK_LEFT,   JOYSTICK_LEFT_PIN, 0, false, false},
  {JOYSTICK_DOWN,   JOYSTICK_DOWN_PIN, 0, false, false},
  {JOYSTICK_RIGHT,  JOYSTICK_RIGHT_PIN, 0, false, false},
};

uint32_t Joystick_prevTime;

void Joystick_Init(){
  for(int i=0;i<JOYSTICK_AMOUNT;i++){
    pinMode(buttons[i].pin, INPUT_PULLUP);
  }
  Joystick_prevTime = millis();
}

void Joystick_Check(){
  uint16_t dt = millis() - Joystick_prevTime;
  Joystick_prevTime = millis();

  for(int i=0;i<JOYSTICK_AMOUNT;i++){
    if(digitalRead(buttons[i].pin) == false){
      buttons[i].pressedTime += dt;
      if(buttons[i].pressedTime >= JOYSTICK_DEBOUNCETIME){
        buttons[i].pressedTime = JOYSTICK_DEBOUNCETIME;
        buttons[i].isPressed = true;
      }
    } else {
        buttons[i].pressedTime = 0;
        buttons[i].isPressed = false;
        buttons[i].isPressChecked = false;
    }
  }
}

bool Joystick_isButtonPressed(uint8_t code){
    for(int i=0;i<JOYSTICK_AMOUNT;i++){
      if(buttons[i].code == code){
        if(buttons[i].isPressed == true && buttons[i].isPressChecked == false){
          buttons[i].isPressChecked = true;
          return true;
        } else {
          return false;
        }
      }
    }

    return false;
}


