#include "util.h"

namespace config {
  const char *ntp_server = NTP_SERVER;
  const long utc_offset_in_seconds = UTC_OFFSET_IN_SECONDS; // UTC+1
}

#if defined(ESP8266)
const char *current_board = "ESP8266";
#  if !defined(AMPEL_WIFI)
void preinit() {
  // WiFi would be initialized otherwise (on ESP8266), even if unused.
  // see https://github.com/esp8266/Arduino/issues/2111#issuecomment-224251391
  ESP8266WiFiClass::preinitWiFiOff();
}
#  endif
#elif defined(ESP32)
const char *current_board = "ESP32";
#else
const char *current_board = "UNKNOWN";
#endif

//NOTE: ESP32 sometimes couldn't access the NTP server, and every loop would take +1000ms
// ifdefs could be used to define functions specific to ESP32, e.g. with configTime
namespace ntp {
  WiFiUDP ntpUDP;
  NTPClient timeClient(ntpUDP, config::ntp_server, config::utc_offset_in_seconds, 60000UL);
  bool connected_at_least_once = false;

  void initialize() {
    timeClient.begin();
  }

  void update() {
    connected_at_least_once |= timeClient.update();
  }

  void getLocalTime(char *timestamp) {
    timeClient.getFormattedDate(timestamp);
  }

  void setLocalTime(int32_t unix_seconds) {
    char time[23];
    timeClient.getFormattedDate(time);
    Serial.print(F("Current time : "));
    Serial.println(time);
    if (connected_at_least_once) {
      Serial.println(F("NTP update already happened. Not changing anything."));
      return;
    }
    Serial.print(F("Setting UNIX time to : "));
    Serial.println(unix_seconds);
    timeClient.setEpochTime(unix_seconds - seconds());
    timeClient.getFormattedDate(time);
    Serial.print(F("Current time : "));
    Serial.println(time);
  }
}

void Ampel::showFreeSpace() {
  Serial.print(F("Free heap space : "));
  Serial.print(ESP.getFreeHeap());
  Serial.println(F(" bytes."));
  Serial.print(F("Max free block size : "));
  Serial.print(esp_get_max_free_block_size());
  Serial.println(F(" bytes."));
  Serial.print(F("Heap fragmentation : "));
  Serial.print(esp_get_heap_fragmentation());
  Serial.println(F(" %"));
}

char sensorId[10]; // e.g "ESPxxxxxx\0"
char macAddress[18]; // e.g "XX:XX:XX:XX:XX:XX\0"
uint8_t mac[6];

char* getMacString() {
  WiFi.macAddress(mac);
  // Get all 6 bytes of ESP MAC
  snprintf(macAddress, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4],
      mac[5]);
  return macAddress;
}

char* getSensorId() {
  WiFi.macAddress(mac);
  // Get last 3 bytes of ESP MAC (worldwide unique)
  snprintf(sensorId, sizeof(sensorId), "ESP%02x%02x%02x", mac[3], mac[4], mac[5]);
  return sensorId;
}

Ampel::Ampel() :
    board(current_board), sensorId(getSensorId()), macAddress(getMacString()), max_loop_duration(0) {
  sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F("1618829570 (Sets time to the given UNIX time)"));
  sensor_console::defineCommand("free", Ampel::showFreeSpace, F("(Displays available heap space)"));
  sensor_console::defineCommand("reset", []() {
    ESP.restart();
  }, F("(Restarts the ESP)"));
}

Ampel ampel;