#include "AiEsp32RotaryEncoder.h"
#include "Arduino.h"

#if defined(ESP8266)
#define ROTARY_ENCODER_A_PIN D6
#define ROTARY_ENCODER_B_PIN D5
#define ROTARY_ENCODER_BUTTON_PIN D7
#else
#define ROTARY_ENCODER_A_PIN 32
#define ROTARY_ENCODER_B_PIN 21
#define ROTARY_ENCODER_BUTTON_PIN 25
#endif
#define ROTARY_ENCODER_VCC_PIN -1

AiEsp32RotaryEncoder rotaryEncoder = AiEsp32RotaryEncoder(ROTARY_ENCODER_A_PIN, ROTARY_ENCODER_B_PIN, ROTARY_ENCODER_BUTTON_PIN, ROTARY_ENCODER_VCC_PIN, 4);

#define LED1_PIN 23
#define LED2_PIN 19

void rotary_onButtonClick() {
  static unsigned long lastTimePressed = 0;
  if (millis() - lastTimePressed < 500) {
    return;
  }
  lastTimePressed = millis();
  Serial.print("Button pressed ");
  Serial.print(millis());
  Serial.println(" milliseconds after restart");
}

void rotary_loop() {
  if (rotaryEncoder.encoderChanged()) {
    int encoderValue = rotaryEncoder.readEncoder();
    Serial.print("Step Increment: ");
    Serial.println(encoderValue);

    // Handle rotation direction
    int direction = encoderValue > 0 ? 1 : -1;

    // Wrap around after 20
    if (abs(encoderValue) >= 20) {
      encoderValue = 0;
      rotaryEncoder.setEncoderValue(encoderValue); // Reset encoder value
    }

    if (abs(encoderValue) >= 11 && abs(encoderValue) <= 20) {
      if (encoderValue <= 15) {
        digitalWrite(LED1_PIN, HIGH);
        delay(50);
        digitalWrite(LED1_PIN, LOW);
        digitalWrite(LED2_PIN, LOW);
        Serial.println("LED1 ON");
      } else {
        digitalWrite(LED1_PIN, HIGH);
        delay(50);
        digitalWrite(LED1_PIN, LOW);
        digitalWrite(LED2_PIN, HIGH);
        Serial.println("LED1 and LED2 ON");
      }
    } else {
      digitalWrite(LED1_PIN, LOW);
      digitalWrite(LED2_PIN, LOW);
      Serial.println("LEDs OFF");
    }

    // Adjust step counting based on direction
    encoderValue *= direction;
    Serial.print("Adjusted Step Increment: ");
    Serial.println(encoderValue);
  }

  if (rotaryEncoder.isEncoderButtonClicked()) {
    rotary_onButtonClick();
  }
}



void IRAM_ATTR readEncoderISR() {
  rotaryEncoder.readEncoder_ISR();
}

void setup() {
  Serial.begin(115200);
  rotaryEncoder.begin();
  rotaryEncoder.setup(readEncoderISR);
  rotaryEncoder.setBoundaries(0, 20, false);

  pinMode(LED1_PIN, OUTPUT);
  pinMode(LED2_PIN, OUTPUT);
}

void loop() {
  rotary_loop();
  delay(50);
}