#include "flash.h"
#include "nvs_flash.h"


const char LOGTAG[] = "nvs storage";
static char flashInits = false;

void flash_init()
{
    if (flashInits)
    {
        return;
    }
    
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ESP_ERROR_CHECK(nvs_flash_init());
    }
    flashInits = 1;
}

void flash_init_partition(const char *partitionName)
{
    ESP_ERROR_CHECK(nvs_flash_init_partition(partitionName));
}

void flash_write_byte(const char *partitionName,const char *varName, void *data, unsigned int size)
{
    nvs_handle_t my_handle;
    nvs_open(partitionName,NVS_READWRITE,&my_handle);
    nvs_set_blob(my_handle,varName,data,size);
    nvs_commit(my_handle);
    nvs_close(my_handle);
}

unsigned int flash_read_byte(const char *partitionName,const char *varName, void *data, unsigned int size)
{
    nvs_handle_t my_handle;
    nvs_open(partitionName,NVS_READONLY,&my_handle);
    nvs_get_blob(my_handle,varName,data,&size);
    nvs_close(my_handle);
    return size;
}

void flash_erase_partition(const char *partitionName)
{
    ESP_ERROR_CHECK(nvs_flash_erase_partition(partitionName));
}

void flash_deinit()
{
ESP_ERROR_CHECK(nvs_flash_deinit());
flashInits = 0;
}