#include "fileSystem.h"
#include <FS.h>
#include <LittleFS.h>

static const char* tag = "fs";

void Init_File_System(void)
{
  if(!LittleFS.begin()){
    ESP_LOGE(tag, "An Error occured while mounting LittleFS");
    return;
  }

  // To format all space in LITTLEFS
  // LITTLEFS.format()

  // Get all information of your LITTLEFS
  ESP_LOGD(tag, "File system info.");
  ESP_LOGD(tag, "Total: %d, Used: %d, Free:%d", LittleFS.totalBytes(), LittleFS.usedBytes(), LittleFS.totalBytes() - LittleFS.usedBytes());

  // Open dir folder
  File dir = LittleFS.open("/");

  // Cycle all the content
  printAllFiles();
}

void getAllDirectories(String directoryList[], int& count) 
{
  File root = LittleFS.open("/");
  if (!root.isDirectory()) { return; }       // Root is not a directory

  directoryList[0] = "/";
  count = 1;

  File file = root.openNextFile();
  while (file) {
    if (file.isDirectory()) {
      directoryList[count] = '/' + String(file.name());
      count++;
    }
    file = root.openNextFile();
  }

  root.close();
}

void printFilesInDirectories(String directoryList[], int count) 
{
  for (int i = 0; i < count; i++) {
    ESP_LOGD(tag, "Dir: %s", directoryList[i].c_str());

    File dir = LittleFS.open(directoryList[i]);
    File file = dir.openNextFile();
    while (file) {
      if (!file.isDirectory()) {
        ESP_LOGD(tag, "    File: %s", file.name());
      }
      file = dir.openNextFile();
    }
    dir.close();
  }
}

void printAllFiles(void) 
{
  String directories[8];
  int dirCount = 0;

  getAllDirectories(directories, dirCount);
  
  ESP_LOGD(tag, "File System Listing:");
  printFilesInDirectories(directories, dirCount);
}