#include <U8g2lib.h>
#include <Wire.h>
#include "ErriezRotaryFullStep.h"

#include "Menu.h"
#include "Item.h"

U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);

const byte ROTARY_PIN1 = 2;
const byte ROTARY_PIN2 = 3;
const byte SWITCH = 4;

RotaryFullStep rotary(ROTARY_PIN1, ROTARY_PIN2, false, 150);

const byte NUMBER_OF_ITEMS = 0;
const byte NUMBER_OF_SUBMENUS = 5;

Menu menu(&u8g2, "main", 5);

Menu submenus[NUMBER_OF_SUBMENUS]{
  Menu(&u8g2, "[1] 1.1 10", 0, 3),
  Menu(&u8g2, "[2] LFO 19.1", 0),
  Menu(&u8g2, "[3] Start =", 0),
  Menu(&u8g2, "[4] End 23.1", 0),
  Menu(&u8g2, "SETTINGS", 0),
};

Item T1Items[3]{
  Item("item 1"),
  Item("item 2"),
  Item("item 3"),
};

byte previousSelectedItem = -1;

void setup() {
  Serial.begin(9600);

  u8g2.begin();
  u8g2.setFont(u8g2_font_pressstart2p_8r);
  u8g2.setFontMode(1);

  pinMode(SWITCH, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(ROTARY_PIN1), rotaryInterrupt, CHANGE);
  attachInterrupt(digitalPinToInterrupt(ROTARY_PIN2), rotaryInterrupt, CHANGE);

  for (byte i = 0; i < 3; i++) {
    submenus[0].addItem(i, &T1Items[i]);
  }

  for (byte i = 0; i < NUMBER_OF_SUBMENUS; i++) {
    menu.addSubmenu(i, &submenus[i]);
  }

  menu.display();
}

void checkSwitch()
{
  if (digitalRead(SWITCH) == 0) {
    menu.select();
  }
}

void rotaryInterrupt()
{
  int rotaryState = rotary.read();
  
  if (rotaryState > 0) {
    menu.down();
  } else if (rotaryState < 0) {
    menu.up();
  }
}

void loop() {
  checkSwitch();

  Menu *currentMenu = menu.getCurrentMenu();

  if (menu.hasChanged()) {
    menu.display();
    menu._hasChanged = false;
  }
  /* byte selectedItem = menu.getSelectedItem();

  if (previousSelectedItem != selectedItem) {
    menu.display();
    previousSelectedItem = selectedItem;
  } */
}