#include <Joystick.h>
#include <Matrix.h>

Joystick joystick;

// These defines match the board schematic
#define ENC1 2, 4
#define ENC2 3, 5

// Matrix defines
#define R0 6
#define R1 7
#define R2 8
#define R3 9
#define R4 10
#define C0 A3
#define C1 A2
#define C2 A1
#define C3 A0

#define BTN1  R0,C0
#define BTN2  R1,C0
#define BTN3  R2,C0
#define BTN4  R3,C0
#define BTN5  R4,C0
#define BTN6  R0,C1
#define BTN7  R1,C1
#define BTN8  R2,C1
#define BTN9  R3,C1
#define BTN10 R0,C2
#define BTN11 R1,C2
#define BTN12 R2,C2
#define BTN13 R3,C2
#define BTN14 R0,C3
#define BTN15 R1,C3
#define BTN16 R2,C3
#define BTN17 R3,C3
#define KBTN1 R4,C1
#define KBTN2 R4,C2
#define KBTN3 R4,C3

void setup() {
  // Encoders
  joystick.AddEncoder(ENC1, 4, ENCODER_PULSED_SPLIT);
  joystick.AddEncoder(ENC2, 4, ENCODER_PULSED_SPLIT);  
                  
  // We will add the 2-stage "key buttons" in a slightly odd order
  // in order to keep columns together for faster scanning.
  uint8_t columns[] = {C0, C1, C2, C3};
  Matrix* matrix = new Matrix(columns, 4);
  
  // Flight modes
  joystick.AddMatrixButton(BTN1, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN2, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN3, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN4, matrix, BUTTON_PASSTHRU);

  // Lights and Doors
  joystick.AddMatrixButton(BTN5, matrix, BUTTON_PULSED_DOUBLE_ACTION);
  joystick.AddMatrixButton(BTN6, matrix, BUTTON_PULSED_DOUBLE_ACTION_SPLIT);
  joystick.AddMatrixButton(BTN7, matrix, BUTTON_PULSED_DOUBLE_ACTION_SPLIT);

  // Mining modules (plus first keybutton)
  joystick.AddMatrixButton(BTN8, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN9, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(KBTN1, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN10, matrix, BUTTON_PASSTHRU);

  // HUD modes
  joystick.AddMatrixButton(BTN11, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN12, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN13, matrix, BUTTON_PASSTHRU);

  // Flight modes (and latter 2 keybuttons)
  joystick.AddMatrixButton(KBTN2, matrix, BUTTON_PASSTHRU);
  joystick.AddMatrixButton(BTN14, matrix, BUTTON_PULSED_DOUBLE_ACTION_SPLIT);
  joystick.AddMatrixButton(BTN15, matrix, BUTTON_PULSED_DOUBLE_ACTION_SPLIT);
  joystick.AddMatrixButton(BTN16, matrix, BUTTON_PULSED_DOUBLE_ACTION_SPLIT);
  joystick.AddMatrixButton(BTN17, matrix, BUTTON_PULSED_DOUBLE_ACTION_SPLIT);
  joystick.AddMatrixButton(KBTN3, matrix, BUTTON_PASSTHRU);

  joystick.Init();
}

void loop() {
  joystick.Update();
}
