/*  Rui Santos & Sara Santos - Random Nerd Tutorials - https://RandomNerdTutorials.com/esp32-lvgl-ebook/
    THIS EXAMPLE WAS TESTED WITH THE FOLLOWING HARDWARE:
    1) ESP32-2432S028R 2.8 inch 240×320 also known as the Cheap Yellow Display (CYD): https://makeradvisor.com/tools/cyd-cheap-yellow-display-esp32-2432s028r/
      SET UP INSTRUCTIONS: https://RandomNerdTutorials.com/cyd-lvgl/
    2) REGULAR ESP32 Dev Board + 2.8 inch 240x320 TFT Display: https://makeradvisor.com/tools/2-8-inch-ili9341-tft-240x320/ and https://makeradvisor.com/tools/esp32-dev-board-wi-fi-bluetooth/
      SET UP INSTRUCTIONS: https://RandomNerdTutorials.com/esp32-tft-lvgl/
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#define MAIN

/*  Install the "lvgl" library version 9.X by kisvegabor to interface with the TFT Display - https://lvgl.io/
    *** IMPORTANT: lv_conf.h available on the internet will probably NOT work with the examples available at Random Nerd Tutorials ***
    *** YOU MUST USE THE lv_conf.h FILE PROVIDED IN THE LINK BELOW IN ORDER TO USE THE EXAMPLES FROM RANDOM NERD TUTORIALS ***
    FULL INSTRUCTIONS AVAILABLE ON HOW CONFIGURE THE LIBRARY: https://RandomNerdTutorials.com/cyd-lvgl/ or https://RandomNerdTutorials.com/esp32-tft-lvgl/   */
#include <lvgl.h>

/*  Install the "TFT_eSPI" library by Bodmer to interface with the TFT Display - https://github.com/Bodmer/TFT_eSPI
    *** IMPORTANT: User_Setup.h available on the internet will probably NOT work with the examples available at Random Nerd Tutorials ***
    *** YOU MUST USE THE User_Setup.h FILE PROVIDED IN THE LINK BELOW IN ORDER TO USE THE EXAMPLES FROM RANDOM NERD TUTORIALS ***
    FULL INSTRUCTIONS AVAILABLE ON HOW CONFIGURE THE LIBRARY: https://RandomNerdTutorials.com/cyd-lvgl/ or https://RandomNerdTutorials.com/esp32-tft-lvgl/   */
#include <TFT_eSPI.h>


#include "weifi.h"
#include "mqtt.h"
// #include "handlebme280.h"
#include "grafik.h"
// #include "interpolation.h"
#include "main.h"

#include <locale.h>

#define NTPREADTIME 1000

long bmeReadtimer = 0;
long updatetimer = 0;


int currentSecond = -1;

void updateDateTime(struct tm tinfo);

void setBMEreadtime(int time) {
  bmeReadTime = time * 1000;
}

void setUpdatetime(int time) {
  updateTime = time * 1000;
}

void setup() {
  setlocale(LC_ALL, "de_DE");
  String LVGL_Arduino = String("LVGL Library Version: ") + lv_version_major() + "." + lv_version_minor() + "." + lv_version_patch();
  Serial.begin(115200);
  delay (1000);
  Serial.println(LVGL_Arduino);

//  initBME280();

  // Start LVGL
  setup_grafik();
  Serial.println("LVGL started");

//  bmedata = readBME280();
//  bmedata.hum = getRelativeFeuchte(bmedata.temp, bmedata.hum);
//  bmedata.temp = bmedata.temp - tempOffset;
  arcTemp.value =  bmedata.temp;
  arcHum.value =  bmedata.hum;
  delay(1000);

  // Function to draw the GUI
  lv_create_main_gui();
  Serial.println("Main GUI created");

  // Start WiFi
  connectToWifi();
  
  // Start MQTT
  setup_mqtt();
  
  // Get the time
  timeinfo = gettheTime(NTPREADTIME);
  updateDateTime(timeinfo);
  
  bmeReadtimer = millis();
  
  drawChart();
  showResetTime(timeinfo);

/*
  // Register print function for debugging
  lv_log_register_print_cb(log_print);
  Serial.println("Print function registered");

  // Function to draw the GUI
  lv_create_main_gui();
  Serial.println("Main GUI created");
*/  
  delay(1000);
  
  /* Test Routinen
  const float tsttemp[] = {27.7, 26.9, 26.7, 26.7, 26.0};
  const float tsthum[] = {62.0, 53.0,  50.0, 48.0, 39.0};
  for (int i = 0; i < 5; i++) {
    Serial.printf("%d  temp: %.1f   hum: %.1f    relF: %d\n", i, tsttemp[i], tsthum[i], getRelativeFeuchte(tsttemp[i], tsthum[i]));
  }

  while (1) {
    delay(1000);
  }
  */
}

void loop() {
  timeinfo = gettheTime(NTPREADTIME);
  if (timeinfo.tm_sec == 0) {  // minute over
    updateDateTime(timeinfo);
 }
  if (millis() - bmeReadtimer > bmeReadTime) {
    bmeReadtimer = millis();
    // bmedata = readBME280();
    // float tmess = bmedata.temp;
    // float hmess = bmedata.hum;
    // bmedata.hum = getRelativeFeuchte(bmedata.temp, bmedata.hum);
    // bmedata.temp = bmedata.temp - tempOffset;
    // doPublish(bmedata.temp, bmedata.hum, tmess, hmess);
  }
  if (millis() - updatetimer > updateTime) {
    updatetimer = millis();
    updatechartData(bmedata.temp+arcTemp.value_offset, bmedata.hum+arcHum.value_offset);
    setValuetoArc(arcTemp, bmedata.temp+arcTemp.value_offset);
    setValuetoArc(arcHum, bmedata.hum+arcHum.value_offset);
  }

  checkMQTT();
//  if (!client.connected())
//   {
//     reconnect();
//   }
//   client.loop();


  server.handleClient();
  ElegantOTA.loop();

  lv_task_handler();  // let the GUI do its work
  lv_tick_inc(5);     // tell LVGL how much time has passed
  delay(5);           // let this time pass
}

void updateDateTime(struct tm tinfo) {
  char time[6];
  static char date[50];
  strftime(time, 6, "%H:%M", &tinfo);
  int wd = tinfo.tm_wday;
  int mo = tinfo.tm_mon;
  int day = tinfo.tm_mday;  
  int year = tinfo.tm_year + 1900;
  sprintf(date, "%s, %d. %s %d", wday[wd], day, month[mo], year);
  setDateTime(time, date);
  // Check if day has just changed
  if (timeinfo.tm_hour = 0 && timeinfo.tm_min == 0 && timeinfo.tm_sec == 0) {
    esp_restart();
  }


}
