#include <WiFi.h>
#include "time.h"
#include <sntp.h>

const char* ssid       = "Wokwi-GUEST";
const char* password   = "";

const char* ntpServer1 = "europe.pool.ntp.org";
const char* ntpServer2 = "time.nist.gov";
const char* time_zone = "CET-1CEST,M3.5.0,M10.5.0/3";  // TimeZone rule for Europe/Rome including daylight adjustment rules (optional)

bool timeSynced = false;

tm localTime() {
  time_t now;
  time(&now);
  tm timeinfo;
  localtime_r(&now, &timeinfo);
  return timeinfo;
}

void printLocalTime() {
  tm timeinfo = localTime();
  static uint8_t lastSecond;
  if (timeinfo.tm_sec == lastSecond) return;
  lastSecond = timeinfo.tm_sec;
  Serial.println(&timeinfo, "%H:%M:%S");
}

// Callback function (get's called when time adjusts via NTP)
void timeavailable(timeval *t) {
  time_t now;
  time(&now);
  Serial.printf("Got time adjustment from NTP! %lu %lu\r\n", t->tv_sec, now);
  timeSynced = true;
}

void setupNTP() {
  sntp_set_time_sync_notification_cb( timeavailable );
  sntp_set_sync_interval(15000);
  configTzTime(time_zone, ntpServer1);
}

void setupWiFi() {
  WiFi.onEvent([](arduino_event_id_t event, arduino_event_info_t info){
    Serial.println("WiFi Connected");
  }, ARDUINO_EVENT_WIFI_STA_GOT_IP);
  WiFi.begin(ssid, password);
}

void setup() {
  Serial.begin(115200);
  setupWiFi();
  setupNTP();
}

void loop() {
  printLocalTime();
  delay(10); // wokwi delay
}