#ifdef ESP8266
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif

#include <time.h>
// Timezone definition to get properly time from NTP server
#define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"
struct tm Time;

////////////////////////////////  NTP Time  /////////////////////////////////////////
void getUpdatedtime(const uint32_t timeout)
{
  uint32_t start = millis();
  do
  {
    time_t now = time(nullptr);
    Time = *localtime(&now);
  } while (millis() - start < timeout && Time.tm_year <= (1970 - 1900));
}



void funzione_orologio()
{
  
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);

  for (int i = 0; i < 5; i++)
  {
    // The variable now contains the system time as Unix Time (number of seconds since 01/01/1970)
    time_t now = time(nullptr);
    // The instruction localtime get the value of now
    // and fit the members of struct tm t, so t.tm_hour
    // will be equal to actual hour, t.tm_min to minutes etcetc.
    struct tm t = *localtime(&now);

    Serial.println("Orologio è:");
    Serial.print(t.tm_hour); Serial.print("\t"); Serial.print(t.tm_min); Serial.print("\t"); Serial.println(t.tm_sec);
    int ore = 0; int minuti = 0; int secondi = 0;
    ore = t.tm_hour; minuti = t.tm_min; secondi = t.tm_sec;
    Serial.println("mostro le variabili");
    Serial.print(ore); Serial.print("\t"); Serial.print(minuti); Serial.print("\t"); Serial.println(secondi);
    delay(3000);
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

#ifdef ESP8266
  configTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
#elif defined(ESP32)
  configTzTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
#endif

  // The first time it take some time to sync
  getUpdatedtime(10000);

  funzione_orologio();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(10); // this speeds up the simulation

  static uint32_t printTime;
  if (millis() - printTime > 1000) {
    printTime = millis();
    getUpdatedtime(0);
    char buffer [80];
    /*
      https://cplusplus.com/reference/ctime/strftime/
    */
    strftime (buffer, 80, "Now it's %Ec\n", &Time);
    Serial.printf (buffer);
  }

}