#include <LiquidCrystal_I2C.h>
#include <Ticker.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

int totalMinutes; // Total menit countdown

int countdownValue; // Nilai countdown

void printCountdown();
void stopCountdown();
void startCountdown();
void setCountdown(int inminutes); // Fungsi untuk mengatur nilai countdown

Ticker timer3(printCountdown, 10); // Ticker untuk menghitung countdown

const int resetButtonPin = 7; // Pin untuk tombol reset
const int startButtonPin = 6; // Pin untuk tombol start
const int button10MinPin = 8; // Pin untuk tombol 10 menit
const int button20MinPin = 9; // Pin untuk tombol 20 menit

int resetButtonState = 0;
int lastResetButtonState = 0;
int startButtonState = 0;
int lastStartButtonState = 0;
int button10MinState = 0;
int lastButton10MinState = 0;
int button20MinState = 0;
int lastButton20MinState = 0;

int minutes, seconds;

void setup() {
  pinMode(resetButtonPin, INPUT);
  pinMode(startButtonPin, INPUT);
  pinMode(button10MinPin, INPUT);
  pinMode(button20MinPin, INPUT);

  lcd.begin(16, 2);
  lcd.backlight();
  lcd.print("Countdown: ");
  Serial.begin(9600);
}

void loop() {
  timer3.update();

  resetButtonState = digitalRead(resetButtonPin);
  if (resetButtonState != lastResetButtonState) {
    if (resetButtonState == HIGH) {
      stopCountdown();
    }
    delay(50);
  }
  lastResetButtonState = resetButtonState;

  startButtonState = digitalRead(startButtonPin);
  if (startButtonState != lastStartButtonState) {
    if (startButtonState == HIGH) {
      startCountdown();
    }
    delay(50);
  }
  lastStartButtonState = startButtonState;

  button10MinState = digitalRead(button10MinPin);
  if (button10MinState != lastButton10MinState) {
    if (button10MinState == HIGH) {
      totalMinutes = 10; // Set total menit menjadi 10
      setCountdown(totalMinutes);
    }
    delay(50);
  }
  lastButton10MinState = button10MinState;

  button20MinState = digitalRead(button20MinPin);
  if (button20MinState != lastButton20MinState) {
    if (button20MinState == HIGH) {
      totalMinutes = 20; // Set total menit menjadi 20
      setCountdown(totalMinutes);
    }
    delay(50);
  }
  lastButton20MinState = button20MinState;

  sendLCD();
}

void sendLCD() {
  lcd.setCursor(12, 0);
  lcd.print(minutes / 10);
  lcd.setCursor(13, 0);
  lcd.print(minutes % 10);
  lcd.setCursor(14, 0);
  lcd.print(":");
  lcd.setCursor(15, 0);
  lcd.print(seconds / 10);
  lcd.setCursor(16, 0);
  lcd.print(seconds % 10);
}

void printCountdown() {
  countdownValue--;
  minutes = countdownValue / 60;
  seconds = countdownValue % 60;
  Serial.println(countdownValue);

  if (countdownValue <= 0 ) {
    timer3.stop();
  }
}

void stopCountdown() {
  timer3.stop();
  countdownValue = totalMinutes * 60; // Set ulang nilai countdown saat dihentikan
  Serial.println(countdownValue);
}

void startCountdown() {
  timer3.start();
}

void setCountdown(int SetMinutes) {
  countdownValue = SetMinutes * 60;
}