#include <Huma_Buttons.h>

/* Pins settings */
#define RE_PIN_CLK      35
#define RE_PIN_DT       36
#define RE_PIN_SW       37

#define RE_DEBOUNCE_TIME      10 //ms

typedef enum {
  KEY_UP = (0), KEY_DOWN, KEY_OK, KEY_NONE
} e_Key;

int volatile counter = 0;
int currentStateCLK = HIGH;
int lastStateCLK = HIGH;
String currentDir ="";
static unsigned long g_re_debounce = 0;
uint8_t g_lastRotate = KEY_DOWN;

void LocalHandleRotaryButton(void);

IRAM_ATTR void RotaryEncoderIsr()
{
  int newClk = digitalRead(RE_PIN_CLK);
  int dtValue = digitalRead(RE_PIN_DT);
  if (newClk == LOW && dtValue == HIGH) {
    // Serial.println("Rotated clockwise ⏩");
    counter++;
  }
  if (newClk == LOW && dtValue == LOW) {
    // Serial.println("Rotated counterclockwise ⏪");
    counter--;
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32-S3!");
  Huma_Buttons.add(RE_PIN_SW);
  pinMode(RE_PIN_CLK, INPUT);
  pinMode(RE_PIN_DT, INPUT);

  attachInterrupt(RE_PIN_CLK, RotaryEncoderIsr, CHANGE);
}

void loop() {
  static int lcounter = counter;
  if (counter != lcounter) {
    Serial.print("Counter: "); Serial.println(counter);
    lcounter = counter;
  }
  LocalHandleRotaryButton();
  delay(10); // this speeds up the simulation
}

void LocalHandleRotaryButton(void)
{
#if 0
  static int lastClk = HIGH;
  int newClk = digitalRead(RE_PIN_CLK);
  if (newClk != lastClk) {
    // There was a change on the CLK pin
    lastClk = newClk;
    int dtValue = digitalRead(RE_PIN_DT);
    if (newClk == LOW && dtValue == HIGH) {
      Serial.println("Rotated clockwise ⏩");
    }
    if (newClk == LOW && dtValue == LOW) {
      Serial.println("Rotated counterclockwise ⏪");
    }
  }
#endif
  if (Huma_Buttons.clicked(RE_PIN_SW)) {
    Serial.println("SW clicked!");
    counter = 0;
  }
}