/*
  SD card test for esp32
 
  This example shows how use the utility libraries
 
  The circuit:
    SD card attached to SPI bus as follows:
        SS    = 5;
        MOSI  = 23;
        MISO  = 19;
        SCK   = 18;
 
 
   by Mischianti Renzo <https://www.mischianti.org>
  
   https://www.mischianti.org
*/
// include the SD library:
#include <SPI.h>
#include <SD.h>
 
// WeMos D1 esp8266: D8 as standard
const int chipSelect = SS;

String command;
// String fileName;
 
// void printDirectory(File dir, int numTabs);
 
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 
 
  Serial.print("\nInitializing SD card...");
 
  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!SD.begin(SS)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }
 
  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (SD.cardType()) {
    case CARD_NONE:
      Serial.println("NONE");
      break;
    case CARD_MMC:
      Serial.println("MMC");
      break;
    case CARD_SD:
      Serial.println("SD");
      break;
    case CARD_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }
 
  // print the type and size of the first FAT-type volume
//  uint32_t volumesize;
//  Serial.print("Volume type is:    FAT");
//  Serial.println(SDFS.usefatType(), DEC);
 
  Serial.print("Card size:  ");
  Serial.println((float)SD.cardSize()/1000);
 
  Serial.print("Total bytes: ");
  Serial.println(SD.totalBytes());
 
  Serial.print("Used bytes: ");
  Serial.println(SD.usedBytes());
 
  // File dir =  SD.open("/");
  // printDirectory(dir, 0);
  Serial.println("\n\nIntroduceti o comanda:");
 
}
 
void loop(void) 
{
  if(Serial.available()){
        command = Serial.readStringUntil('\n');
         
        if(command.equals("dir"))
        {
          File dir =  SD.open("/");
          printDirectory(dir, 0);
          Serial.println("\nIntroduceti o comanda:");
        }
        else if(command.equals("list")){
            listFile();
            Serial.println("\nIntroduceti o comanda:");
        }
        else if(command.equals("del")){
          File dir = SD.open("/");
          int index = 0;
          while (true)
          {
            File entry =  dir.openNextFile();
            if (! entry) {
              // no more files
              break;
            }

           

            String path = String(entry.name());

            
            if(SD.remove("/" + path))
            {
              Serial.print(".");
            }
            else
            {
              // Serial.print("x");
              Serial.println(path);
            }
            
            if (index > 30)
            {
              Serial.println("");
              index = 0;
            }

            index++;
          }
            
        }
        else{
            Serial.println("Invalid command");
            Serial.println("\nIntroduceti o comanda:");
        }
    }
}
 
void printDirectory(File dir, int numTabs) {
  while (true) {
 
    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.print(entry.size(), DEC);
      time_t lw = entry.getLastWrite();
      struct tm * tmstruct = localtime(&lw);
      Serial.printf("\tLAST 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);
    }
    entry.close();
  }
}


void listFile()
{
  String fileName;
  
  Serial.println("\n\nIntroduceti numele fisierului");
  delay(200);
  while(fileName.length() == 0)
  {
    if(Serial.available())
    {
        fileName = Serial.readStringUntil('\n');
    }
  }

  Serial.print("fileName >>");
  Serial.print(fileName);
  Serial.println("<<");

  File dataFile = SD.open("/" + fileName);

  if (dataFile) 
  {
    while (dataFile.available()) 
    {
      Serial.write(dataFile.read());
    }
    dataFile.close();
  }

// if the file isn't open, pop up an error:

  else 
  {
    Serial.println("error opening /" + fileName);
  }
}