#include "./lib/meshtalos.h"
#include "esp_err.h"
#include "network.h"
#include <esp_event.h>
#include <esp_littlefs.h>
#include <esp_log.h>
#include <nvs_flash.h>

#define BLOCKSIZE 4096

const char *TAG = "main";

void fatal_err(int code) {
  while (1) {
    ESP_LOGE(TAG, "fatal err: %d", code);
    sleep(5);
  }
}

void app_main(void) {

  /*  event initialization */
  netif_start();
  ESP_LOGI(TAG, "network inited");

  esp_vfs_littlefs_conf_t conf = {.base_path = "/lfs",
                                  .partition_label = "storage",
                                  .format_if_mount_failed = true,
                                  .dont_mount = false,
                                  .partition = NULL};
  esp_err_t ret = esp_vfs_littlefs_register(&conf);
  if (ret != ESP_OK) {
    if (ret == ESP_FAIL) {
      ESP_LOGE(TAG, "Failed to mount or format filesystem");
    } else if (ret == ESP_ERR_NOT_FOUND) {
      ESP_LOGE(TAG, "Failed to find LittleFS partition");
    } else {
      ESP_LOGE(TAG, "Failed to initialize LittleFS (%s)", esp_err_to_name(ret));
    }
    return;
  }

  struct Meshtalos *control = mtsh_init();
  if (control == NULL) {
    fatal_err(1);
  }
  mtsh_listen(control, "http://0.0.0.0:80");
}
