#include "LiquidCrystal_I2C.h"
#include "RTClib.h"
#include "DHT.h"

#define menuBtn A0
#define plusBtn A1
#define minusBtn A2

LiquidCrystal_I2C lcd(0x27, 16, 2);
RTC_DS1307 clock;
DHT tm(5, DHT22);

int pressCount, h, m;
long ms;
bool changeHrs, changeMins;

void setup() {
  pinMode(menuBtn, INPUT_PULLUP);
  pinMode(plusBtn, INPUT_PULLUP);
  pinMode(minusBtn, INPUT_PULLUP);

  lcd.init();
  lcd.backlight();
  tm.begin();
  clock.begin();
  clock.adjust(DateTime(F(__DATE__), F(__TIME__)));
  
  h = 2;
}

void loop() {
  if (millis() >= ms)
  {
    lcd.noBacklight();
  }
  else
  {
    lcd.backlight();
  }
  
  DateTime dt = clock.now() + TimeSpan(0, h, m, 0);
  int hour = dt.hour();
  int minute = dt.minute();
  int second = dt.second();
  float temp = tm.readTemperature();

  lcd.setCursor(4, 0);

  if (hour <= 9)
  {
    lcd.print(0);
  }

  lcd.print(hour + String(":"));

  if (minute <= 9)
  {
    lcd.print(0);
  }

  lcd.print(minute + String(":"));
  
  if (second <= 9)
  {
    lcd.print(0);
  }

  lcd.print(second);

  if (h == 24)
  {
    h = 0;
  }
  else if (m == 60)
  {
    m = 0;
  }

  if (!analogRead(menuBtn))
  {
    delay(100);
    pressCount++;
    ms = millis() + 30000;
  }

  lcd.home();

  switch (pressCount)
  {
    case 1:
      changeMins = false;
      changeHrs = true;
      break;

    case 2:
      changeHrs = false;
      changeMins = true;
      break;

    case 3:
    case 0:
      pressCount = 0;
      changeHrs, changeMins = false;
      lcd.print("   ");
      break;
  }

  if (changeHrs)
  {
    lcd.print("hr ");

    if (!analogRead(plusBtn) && analogRead(minusBtn))
    {
      delay(100);
      h++;
      ms = millis() + 30000;
    }
    else if (!analogRead(minusBtn) && analogRead(plusBtn))
    {
      delay(100);
      h--;
      ms = millis() + 30000;
    }
  }
  else if (changeMins)
  {
    lcd.print("min");

    if (!analogRead(plusBtn) && analogRead(minusBtn))
    {
      delay(100);
      m++;
      ms = millis() + 30000;
    }
    else if (!analogRead(minusBtn) && analogRead(plusBtn))
    {
      delay(100);
      m--;
      ms = millis() + 30000;
    }
  }

  lcd.setCursor(4, 1);
  
  if (!(changeHrs || changeMins))
  {
    lcd.print(temp + String(" C"));
  }
  else
  {
    lcd.print("        ");
  }
}
GND5VSDASCLSQWRTCDS1307+