#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <DHT.h>
#include <RTClib.h>
#include <Wire.h>

// Hardware define
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 4
#define CS_PIN 5    // Adjust according to your wiring
#define DATA_PIN 23 // Adjust according to your wiring
#define CLK_PIN 18  // Adjust according to your wiring
#define DHT_PIN 4   // DHT22 data pin
#define DHT_TYPE DHT22

// Create objects
MD_Parola display = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
DHT dht(DHT_PIN, DHT_TYPE);
RTC_DS3231 rtc;

// Variables for timing
unsigned long previousMillis = 0;
const long interval = 5000; // Switch display every 5 seconds
bool showTime = true;

void setup() {
  Serial.begin(115200);
  
  // Initialize LED Matrix
  display.begin();
  display.setIntensity(0);
  display.displayClear();
  
  // Initialize DHT22
  dht.begin();
  
  // Initialize RTC
  if (!rtc.begin()) {
    Serial.println("RTC tidak terdeteksi!");
    while (1);
  }
  
  // Uncomment line below to set RTC time (run once, then comment again)
  // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  
  display.setTextAlignment(PA_CENTER);
}

void loop() {
  unsigned long currentMillis = millis();
  
  // Switch between time and sensor readings every 5 seconds
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    showTime = !showTime;
    display.displayClear();
  }
  
  if (showTime) {
    displayTime();
  } else {
    displayTempHum();
  }
  
  if (display.displayAnimate()) {
    display.displayReset();
  }
}

void displayTime() {
  // DateTime now = rtc.now();
  // char timeStr[6];
  // sprintf(timeStr, "%02d:%02d", now.hour(), now.minute());
  // display.setTextAlignment(PA_CENTER);
  // display.print(timeStr);
}

void displayTempHum() {
  // float temperature = dht.readTemperature();
  // float humidity = dht.readHumidity();
  
  // if (isnan(temperature) || isnan(humidity)) {
  //   display.print("Error");
  //   return;
  // }
  
  // char sensorStr[10];
  // sprintf(sensorStr, "%2.1fC %2.0f%%", temperature, humidity);
  // display.setTextAlignment(PA_CENTER);
  // display.print(sensorStr);
}
GND5VSDASCLSQWRTCDS1307+