#include <stdio.h>

#include "connectivity.h"
#include "epd_driver.h"
#include "esp_task.h"
#include "esp_task_wdt.h"
#include "fonts/opensans16.h"
#include "mapView.h"
#include "nvs_flash.h"
#include "sdkconfig.h"
#include "smartconfig.h"
#include "utilities.h"

void nvs_init(void) {
  esp_err_t ret = nvs_flash_init();
  if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
      ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
    ESP_ERROR_CHECK(nvs_flash_erase());
    ret = nvs_flash_init();
  }
  ESP_ERROR_CHECK(ret);
}

void splash_screen(void) {
  epd_init();
  nvs_init();
  epd_poweron();
  epd_clear();

  int32_t x = 100;
  int32_t y = 100;
  char buffer[100];
  sprintf(buffer, "Connecting to SSDI: %s", CONFIG_WIFI_SSID);
  writeln(&OpenSans16, buffer, &x, &y, NULL);
  auto ret = init_wifi();
  if (ret != 0) {
    epd_clear();
    writeln(&OpenSans16, "Failed to connect to WiFi.", &x, &y, NULL);
    epd_poweroff();
    while (1) {
      ///
    };
  }
  epd_poweroff();
}

void setup(void) {
  splash_screen();

  // init_smartconfig();
  xTaskCreatePinnedToCore(mapView, "mapView", 4096, NULL, 5, NULL, 1);
}

void loop(void) {
  vTaskDelay(pdMS_TO_TICKS(100));
}

extern "C" void app_main(void) {
  setup();
  while (1) {
    loop();
  }
}
