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

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>


#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int tm_hour;
int tm_mins;
int tm_secs;

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

const char* ntpServer1 = "pool.ntp.org";
const char* ntpServer2 = "time.nist.gov";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

const char* time_zone = "CET-1CEST,M3.5.0,M10.5.0/3";  // "JST-9";//TimeZone rule for Europe/Rome including daylight adjustment rules (optional)

void printOLED(char *time, char *date, int x) {
  display.clearDisplay();

  display.setTextSize(2);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(x,2);
  //display.println(F("17:06:55"));
  display.println(time);
  
  display.setTextSize(1);             // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE);        // Draw white text
  display.setCursor(0,20);             // Start at top-left corner
  display.print(date);

  /*
  display.setTextColor(SSD1306_WHITE); // Draw 'inverse' text, origi: display.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
  display.println(3.141592);
    */


  display.display();
  //delay(2000);
}


void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("No time available (yet)");
    return;
  }
  tm_hour = timeinfo.tm_hour;
  tm_mins = timeinfo.tm_min;
  tm_secs = timeinfo.tm_sec;
  
  struct tm * mytime;
  time_t rawtime;
  char date_char [30];
  time (&rawtime);
  mytime = localtime (&rawtime);

  strftime (date_char,80,"%a, %B %e %G",mytime);

  int offset;
  String time_str;
  time_str = String(tm_hour) + ":" + String(tm_mins) + ":" + String(tm_secs);

  if(tm_hour<10){
      offset = 26;
   } else {
      offset = 14;  
  }
  char time_char[10];
  sprintf (time_char, "%d:%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
  
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
  //Serial.println(buffer);
  Serial.println(time_char);
  printOLED(time_char, date_char, offset);
}

// Callback function (get's called when time adjusts via NTP)
void timeavailable(struct timeval *t)
{
  Serial.println("Got time adjustment from NTP!");
  printLocalTime();
}

void setup()
{
  Serial.begin(115200);

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  display.clearDisplay();
  display.display();
  
  // set notification call-back function
  sntp_set_time_sync_notification_cb( timeavailable );

  /**
   * NTP server address could be aquired via DHCP,
   *
   * NOTE: This call should be made BEFORE esp32 aquires IP address via DHCP,
   * otherwise SNTP option 42 would be rejected by default.
   * NOTE: configTime() function call if made AFTER DHCP-client run
   * will OVERRIDE aquired NTP server address
   */
  sntp_servermode_dhcp(1);    // (optional)

  /**
   * This will set configured ntp servers and constant TimeZone/daylightOffset
   * should be OK if your time zone does not need to adjust daylightOffset twice a year,
   * in such a case time adjustment won't be handled automagicaly.
   */
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2);

  /**
   * A more convenient approach to handle TimeZones with daylightOffset 
   * would be to specify a environmnet variable with TimeZone definition including daylight adjustmnet rules.
   * A list of rules for your zone could be obtained from https://github.com/esp8266/Arduino/blob/master/cores/esp8266/TZ.h
   */
  configTzTime(time_zone, ntpServer1, ntpServer2);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");
  

  display.display();
}

void loop()
{
  delay(1000);
  printLocalTime();     // it will take some time to sync time :)
}