#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <WiFi.h>
#include <TimeLib.h>
 
#define TFT_DC (2)
#define TFT_CS (5)

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 7*60*60;
const int   daylightOffset_sec = 0;

uint32_t targetTime = 0;
char dateStringBuff[50];
char timeStringBuff[50];  
char WeekStringBuff[50];
char hhStringBuff[10];
char mmStringBuff[10];
char ssStringBuff[10];
uint8_t hh, mm, ss;

void setup() {
  Serial.begin(115200);
  tft.begin();
  tft.setRotation(3);
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  targetTime = millis() + 1000;
}

void loop() {
  printLocalTime();
}

void printLocalTime() {
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    Serial.println("Cannot get local time!");
    return;
  } else {
    Serial.println("ok");
  }
  strftime(dateStringBuff, sizeof(dateStringBuff), "%F", &timeinfo);
  strftime(timeStringBuff, sizeof(timeStringBuff), "%T", &timeinfo);
  strftime(WeekStringBuff, sizeof(WeekStringBuff), "%w", &timeinfo);
  strftime(hhStringBuff, sizeof(hhStringBuff), "%H", &timeinfo);
  strftime(mmStringBuff, sizeof(mmStringBuff), "%M", &timeinfo); 
  strftime(ssStringBuff, sizeof(ssStringBuff), "%S", &timeinfo);
  String HH, MM, SS;
  HH = hhStringBuff;
  MM = mmStringBuff;
  SS = ssStringBuff;
  hh = HH.toInt();
  mm = MM.toInt();
  ss = SS.toInt();

  if (targetTime < millis()) {
    targetTime = millis() + 1000;
    tft.setTextSize(3);
    tft.setCursor(30,50);
    tft.setTextColor(ILI9341_BLUE );
    tft.println(dateStringBuff); 
    tft.setTextSize(3);
    tft.setCursor(30,100);
    tft.setTextColor(0x39C4, ILI9341_BLACK);
    tft.println("88:88:88"); 
    tft.setCursor(30,100);
    tft.setTextColor(ILI9341_RED);
    tft.println(timeStringBuff);
    tft.setTextSize(3);
    tft.setCursor(30,150);
    tft.setTextColor(ILI9341_PURPLE );
    tft.println("Week:" + String(WeekStringBuff)); 
    Serial.println(timeStringBuff);
  }
}