#include "splash_screen.h"
#include <esp_task_wdt.h>
#include <stdio.h>
#include "connectivity.h"
#include "epd_driver.h"
#include "fonts/opensans16.h"
#include "nvs_flash.h"
#include "sdkconfig.h"
#include "sntp_utils.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 wifi_init(void) {
    epd_clear();

    int32_t x = 100;
    int32_t y = 100;
    const int16_t bufferSize = 200;
    char buffer[bufferSize];
    snprintf(buffer, bufferSize, "Connecting to SSDI: %s", CONFIG_WIFI_SSID);
    writeln(&OpenSans16, buffer, &x, &y, NULL);

    esp_err_t ret = init_wifi();
    if (ret != ESP_OK) {
        epd_clear();
        x = 100;
        y = 100;
        snprintf(buffer, bufferSize, "Failed to connect to WiFi: %s", esp_err_to_name(ret));
        writeln(&OpenSans16, buffer, &x, &y, NULL);
        epd_poweroff();
        while (1) {
            vTaskDelay(pdMS_TO_TICKS(100));
        };
    }
}

void time_init(void) {
    epd_clear();

    int32_t x = 100;
    int32_t y = 100;
    const int16_t bufferSize = 200;
    char buffer[bufferSize];
    snprintf(buffer, bufferSize, "Loading SNTP Data...");
    writeln(&OpenSans16, buffer, &x, &y, NULL);

    esp_err_t ret = init_sntp();
    if (ret != ESP_OK) {
        epd_clear();
        x = 100;
        y = 100;
        snprintf(buffer, bufferSize, "Failed to get NTP data and timezone: %s", esp_err_to_name(ret));
        writeln(&OpenSans16, buffer, &x, &y, NULL);
        epd_poweroff();
        while (1) {
            vTaskDelay(pdMS_TO_TICKS(100));
        };
    }
}

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

    epd_poweron();

    wifi_init();
    time_init();

    epd_poweroff();
}
