#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#include "Button.h"

#include "TimerOne.h"

#include "Time.h"

#define SCREEN_WIDTH        128 // OLED display width, in pixels
#define SCREEN_HEIGHT        64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET            -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

//create a Time object
Time currentTime;

// Create Buttons objects on pin 4 and pin3
Button btnG(4);
Button btnB(3);

unsigned long cm;             //current millis

void setup() {
  Serial.begin(9600);
  // initialize and clear display
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }

  display.clearDisplay();

  currentTime.setTime(22,0,30);

  Timer1.initialize(1000000); // Interrupt every 1 second
  Timer1.attachInterrupt(updateTime);

}

void loop() {
  cm=millis();
  btnG.update();
  btnB.update();
  checkButtons();
  display.clearDisplay();
  displayTime();
  display.display();
  delay(100);
}

void displayTime() {
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.print("TIME:");
  display.setCursor(15, 20);
  display.print(currentTime.hours < 10 ? "0" : "");
  display.print(currentTime.hours);
  display.print(":");
  display.print(currentTime.minutes < 10 ? "0" : "");
  display.print(currentTime.minutes);
  display.print(":");
  display.print(currentTime.seconds < 10 ? "0" : "");
  display.print(currentTime.seconds);
}

void checkButtons() {
  // Implement button logic for setting time and alarm
  if (btnB.wasPressed() || btnG.wasPressed())
  {
    setTime();
  }
}

void setTime()
{
  // Handle Hours
  currentTime.seconds=0;
  if(btnG.isPressed())
  {
    currentTime.hours++;
  }
  if (btnG.wasLongPressed() ) {
    static unsigned long pm=cm;
    if((cm-pm)>=200)
    {
      currentTime.hours++;
      pm=cm;
    }
  }
  if(currentTime.hours>23)   currentTime.hours=0;

  // Handle minutes
  if(btnB.isPressed())
  {
    currentTime.minutes++;
  }
  if (btnB.wasLongPressed() ) {
    static unsigned long pm=cm;
    if((cm-pm)>=200)
    {
      currentTime.minutes++;
      pm=cm;
    }
  }
  if(currentTime.minutes>59)   currentTime.minutes=0;
}


//ISR: Interrupt Service Routine:
void updateTime() {
  if(!btnB.wasPressed()) currentTime.incrementSeconds();
}