#include "nvs.h"
#include "esp_log.h"
#include "bottom_half.h"
#include "char_lcd.h"

static const char* TAG = "nvs";

static const char* HWDATA_NAMESPACE = "hwdata";
static HWData hw_data;

bool init_nvs() {
    ESP_LOGI(TAG, "Initializing NVS...");
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // NVS partition was truncated, erase and retry
        ESP_LOGE(TAG, "Failed to init nvs flash: %s.", esp_err_to_name(ret));
        lcd_print(1, 0, "NVS: ");
        lcd_print(1, 4, esp_err_to_name(ret));
        lcd_print(2, 0, "Press Yellow to skip");
        lcd_print(3, 0, "Press Red to erase");

        ButtonKey button;
        while (!( get_button_pressed(&button) && (button == ButtonKey::button_red || button == ButtonKey::button_yellow) )) vTaskDelay(pdMS_TO_TICKS(10));

        lcd_clear();
        
        if (button == ButtonKey::button_yellow) {
            return false;
        }
        if (button == ButtonKey::button_red) {
            ESP_ERROR_CHECK(nvs_flash_erase());
            ret = nvs_flash_init();
        }
    }
    ESP_ERROR_CHECK(ret);

    nvs_handle_t hw_handle;
    ret = nvs_open(HWDATA_NAMESPACE, NVS_READONLY, &hw_handle);
    if (ret == ESP_ERR_NVS_NOT_FOUND) {
        ESP_LOGW(TAG, "Partition \"%s\" has not been initialized. Loading defaults.", HWDATA_NAMESPACE);
        hw_data = HWData();
    } else {
        ESP_ERROR_CHECK(ret);
        hw_data = HWData::load(hw_handle);
        nvs_close(hw_handle);
    }

    ESP_LOGI(TAG, "NVS initialized!");

    return true;
}

HWData& get_hw_data() {
    return hw_data;
}

void save_hw_data(bool force) {
    nvs_handle_t hw_handle;
    ESP_ERROR_CHECK(nvs_open(HWDATA_NAMESPACE, NVS_READWRITE, &hw_handle));
    hw_data.save(hw_handle);
    nvs_close(hw_handle);
}

