#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Arduino.h>
#include <math.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

#define x 35
#define y 34
#define sel 32

bool firstTime = true;
int x_val = 0;
int y_val = 0;
int sel_val = 0;
int selection = 0;
const int sel_count = 4;
String selections[sel_count] = {"Menu", "Setting", "Test1", "Test2"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");

  pinMode(sel, INPUT_PULLUP);

  lcd.init();
  lcd.backlight();
  lcd.clear();

  lcd.print("Di chuyen joystick!");
}

void loop() {
  // put your main code here, to run repeatedly:
  x_val = analogRead(x);
  y_val = analogRead(y);
  sel_val = !(digitalRead(sel));

  if (firstTime) {
    firstTime = false;
    y_val = 20; // arbitrary number for mimicking joystick movement
  }

  // prevent unnessesary update
  if (y_val != 2048) {
    if (y_val == 4095) {
      selection = (selection == 0) ? 0 : selection-1;
    } else if (y_val == 0) {
      selection = (selection == sel_count-1) ? sel_count-1 : selection+1;
    }

    if (selection == sel_count-1) {
      lcd.clear();
      lcd.setCursor(2, 0);
      lcd.print(selections[selection-1]);
      lcd.setCursor(0, 1);
      lcd.print(">");
      lcd.setCursor(2, 1);
      lcd.print(selections[selection]);
    } else {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(">");
      lcd.setCursor(2, 0);
      lcd.print(selections[selection]);
      lcd.setCursor(2, 1);
      lcd.print(selections[selection+1]);
    }

    delay(200);
  }
  if (sel_val == 1) {
    Serial.print("Da chon: ");
    Serial.println(selections[selection]);
    delay(200);
  }

  delay(10); // this speeds up the simulation
}