//SCreen
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

//Rotary Encoder

// Rotary Encoder Inputs
#define inputCLK 2
#define inputDT 5

//int counter = 0;
volatile int currentStateCLK;
volatile int previousStateCLK;

String encdir = "";  //String to be populated with either ClockWise or CounterClockWise

//Variables
volatile byte newLength = 20;
byte currLength = 0;

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void updateEncoder() {
  //read the state of clk
  currentStateCLK = digitalRead(inputCLK);
  if (currentStateCLK != previousStateCLK) {
    previousStateCLK = currentStateCLK;
    byte data = digitalRead(inputDT);
    if (!data && currentStateCLK == LOW) {
      if (newLength < 254)
        newLength = newLength + 1; //clockwise
    } else if (data && currentStateCLK == LOW)  {
      if (newLength > 0) newLength = newLength - 1; //counterclockwise
    }
  }
}


void setup() {
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();

  //RotaryEncoder
  // Set encoder pins as inputs
  pinMode(inputCLK, INPUT_PULLUP);
  pinMode(inputDT, INPUT_PULLUP);

  // Read the initial state of inputCLK
  // Assign to previousStateCLK variable
  previousStateCLK = digitalRead(inputCLK);
  attachInterrupt(digitalPinToInterrupt(inputCLK), updateEncoder, CHANGE);


}

void loop() {

  if (currLength != newLength) {
    currLength = newLength;
    Serial.print(" Length ");
    Serial.println(newLength);
    //Oled
    display.clearDisplay();
    display.setTextSize(1);
    display.setTextColor(WHITE);
    //Timer
    display.setCursor(0, 10);
    display.print("Timer - ");
    display.print(newLength);
    display.println(" Minutes");
    display.display();
  }


}