#include "epd2in7.h"
#include "epdpaint.h"

// b/w e-Paper
#define COLORED     0
#define UNCOLORED   1

Epd epd;
uint64_t us_s_conversion_factor = 1000*1000;  // conversion factor for s to µs
uint64_t DEEP_SLEEP_TIME = 6*60*60;  // time to deep sleep in microseconds (not milliseconds!)

// WiFi
char wiFiSSID[] = "SSID";  // SSID of your network
char wiFiPSK[] = "PRE-SHARED KEY";  //password of your WPA Network

// NTP (Network Time Protocol)
const String ntpServer = "pool.ntp.org";  // address of ntp server; may also be your router, other local service, etc.
const long  gmtOffset_sec = 3600;  // for localization (gmt = greenwich mean time); in germany: 3600
const int   daylightOffset_sec = 3600;  // for daylight saving

// onboard LED
const int LED_ON_WIFI_ERROR = 2;

// style of the frame shown
sFONT TITLE_FONT = Font20;
char TITLE_TEXT[] = "Losung heute";
int TITLE_PADDING_TOP = 10;
sFONT TEXT_FONT = Font12;  // for the daily text
int TEXT_WIDTH = 168;  // width of the box around the text; should be a multiple of the width of the font (eg. Font8 => multiple of 8)
int TEXT_PADDING_TOP = 20;
int TEXT_PADDING_BETWEEN_BLOCKS = 20;  // pixels between the lines
int TEXT_PADDING_BETWEEN_LINES = 1;  // pixels between the lines
sFONT SOURCE_FONT = Font8;  // for the position in bible

void deepSleep() {
  // deep sleep for DEEP_SLEEP_TIME seconds
  esp_sleep_enable_timer_wakeup(DEEP_SLEEP_TIME*us_s_conversion_factor);
  Serial.printf("[ESP32] Entering deep sleep mode for %ds\n", DEEP_SLEEP_TIME);
  esp_deep_sleep_start();  
}

bool gotLosung = false;  // if everything worked and http get returned HTTP 200
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  Serial.println("[INFO] Initializing e-Paper...");
  if (epd.Init() != 0) {
    Serial.println("[FATAL] Failed initializing e-Paper; Exiting...");
    return;
  }
  Serial.println("[INFO] Initialized e-Paper!");

  if(connectWiFi()) {
    Serial.println("[NTP] Getting time...");
    configTime(gmtOffset_sec, daylightOffset_sec, ntpServer.c_str());
    Serial.println("[NTP] Got time.");
  }
  String html = getHTML();
  if(html != "") gotLosung = true;

  if(gotLosung) {
    showDailyText(getLosungFromHTML(html), getLehrtextFromHTML(html), getLosungSourceFromHTML(html), getLehrtextSourceFromHTML(html));
    deepSleep();
  }
}

void loop() {
  if(!gotLosung) {
    if(connectWiFi()) {
      Serial.println("[NTP] Getting time...");
      configTime(gmtOffset_sec, daylightOffset_sec, ntpServer.c_str());
      Serial.println("[NTP] Got time.");
    }

    String html = getHTML();
    if(html != "") gotLosung = true;

    if(gotLosung) {
      showDailyText(getLosungFromHTML(html), getLehrtextFromHTML(html), getLosungSourceFromHTML(html), getLehrtextSourceFromHTML(html));
      deepSleep();
    }
  }
}
