#include <Arduino.h>
#include "abc800_keyboard.h"
#include "abc800_littlefs.h"
#include "abc800_config.h"
#include <ArduinoJson.h> 
#include <FS.h> 
#include "LITTLEFS.h"

static const char TAG[] = __FILE__;
#define FORMAT_LITTLEFS_IF_FAILED true
void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
    Serial.printf("Listing directory: %s\r\n", dirname);

    File root = fs.open(dirname);
    if(!root){
        ESP_LOGE(TAG,"- failed to open directory");
        return;
    }
    if(!root.isDirectory()){
        ESP_LOGE(TAG," - not a directory");
        return;
    }

    File file = root.openNextFile();
    while(file){
        if(file.isDirectory()){
            ESP_LOGD(TAG,"  DIR : ");

#ifdef CONFIG_LITTLEFS_FOR_IDF_3_2
            Serial.println(file.name());
#else
            Serial.print(file.name());
            time_t t= file.getLastWrite();
            struct tm * tmstruct = localtime(&t);
            ESP_LOGD(TAG,"  LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec);
#endif

            if(levels){
                listDir(fs, file.name(), levels -1);
            }
        } else {
            ESP_LOGD(TAG,"  FILE: %s ",file.name());
            ESP_LOGD(TAG,"  SIZE: %d",file.size());

#ifdef CONFIG_LITTLEFS_FOR_IDF_3_2
            Serial.println(file.size());
#else
            time_t t= file.getLastWrite();
            struct tm * tmstruct = localtime(&t);
            ESP_LOGD(TAG,"  LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec);
#endif
        }
        file = root.openNextFile();
    }
}
namespace abc800
{

    void littlefs::setup(){
        //clean FS, for testing
        //SPIFFS.format();

        delay(1000);
        ESP_LOGD(TAG,"TAG");
        if(!LITTLEFS.begin(FORMAT_LITTLEFS_IF_FAILED)){
            ESP_LOGD(TAG,"LITTLEFS Mount Failed");
        }
        listDir(LITTLEFS, "/", 0);

        ESP_LOGD(TAG,"TEST");
        delay(1000);
        
    }
    key800config littlefs::loadconfig(){
        key800config config;
        return (config);   
    }
}