#include <WiFi.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include "sketch.h"

volatile int MEM_TIME = 0;




// WARNING: THE TIME IS SET TO
// Seattle Daylight Time
//
// Go into "sketch.h" to change it




void setup() {
  tft.begin();
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);
  tft.setTextSize(2);
  Serial.begin(115200);
  cls();

  tft.print("Connecting to ");
  tft.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    tft.print(".");
  }
  tft.println("Connected!\n\n");

  configTime(gmtOffset, daylightOffset, ntpServer);

  tft.print("Fetching time ");

  while (time(nullptr) < 1e5) {
    tft.print(time(nullptr));
    delay(1000);
  }

  Serial.println("\nReady!");
  cls();
}

void loop() {
  printLocalTime();
  delay(500);
}


void printLocalTime() {
  struct tm* timeinfo;
  time_t now;
  time(&now);

  timeinfo = localtime(&now);

  if (MEM_TIME != timeinfo->tm_min) {
    MEM_TIME = timeinfo->tm_min;
    cls();

    tft.setCursor(0, 0);
    tft.setTextColor(ILI9341_RED);
    tft.setTextSize(3);
    tft.println("Uhr");
    tft.println(amTime(timeinfo->tm_hour, timeinfo->tm_min));
    tft.setTextColor(ILI9341_BLUE);
    tft.println("\nToday is a...");
    tft.println(timeinfo, "%A");
    tft.setTextSize(2);
    tft.setTextColor(ILI9341_GREEN);
    tft.println("\nAujourd'hui c'est le");
    tft.println(timeinfo, "%d %B 20%y");
  } else Serial.println(timeinfo, "%A %B %d %y %H:%M:%S");

  //drawText(0, ILI9341_GREEN, 1, "Test");
}


void cls() {
  tft.fillScreen(ILI9341_BLACK);
}

String amTime(int hour, int mins) {
  String h = String(hour); String m = String(mins);
  if (mins<10) m = "0" + m;
  if (hour == 0 || hour == 24) return "12:" + m + " AM";
  else if (hour == 12) return "12: " + m + " PM";
  else if (hour < 12) return h + ":" +  m + " AM";
  else if (hour > 12) return String(hour-12) + ":" + m + "PM";
  else throw "frick";
}
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
lcd:VCC
lcd:GND
lcd:CS
lcd:RST
lcd:D/C
lcd:MOSI
lcd:SCK
lcd:LED
lcd:MISO