#include <SD.h>

#define CS 10

void setup() {
  Serial.begin(9600);

  if (!SD.begin(CS)) {
    Serial.println("Initialization error");
    return;
  }
  Serial.println("Initialized");
  printMenu();
}

void loop() {
  if (Serial.available()) {
    int choice = Serial.parseInt();
    while (Serial.available() > 0) {
      Serial.read();
    }
    switch (choice) {
      case 1:
        listFiles();
        break;
      case 2:
        deleteFile();
        break;
      case 3:
        createEmptyFile();
        break;
      case 4:
        writeDataToFile();
        break;
      case 5:
        readFileContent();
        break;
      default:
        Serial.println("Error choice");
        break;
    }
  }
}

void listFiles() {
  Serial.println("List files on SD");
  File root = SD.open("/");
  while (true) {
    File entry =  root.openNextFile();
    if (!entry) {
      break;
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
    } else {
      Serial.println("\t");
    }
    entry.close();
  }
}

void deleteFile() {
  Serial.println("File name:");
  while (Serial.available() == 0) {
  }
  String fileName = Serial.readStringUntil('\n');
  if (SD.remove(fileName)) {
    Serial.println("File deleted successfully");
  } else {
    Serial.println("Error deleting file");
  }
}

void createEmptyFile() {
  Serial.println("File name:");
  while (Serial.available() == 0) {
  }
  String fileName = Serial.readStringUntil('\n');
  File newFile = SD.open(fileName, FILE_WRITE);
  if (newFile) {
    newFile.close();
    Serial.println("Creating was successful");
  } else {
    Serial.println("Error creating file");
  }
}

void writeDataToFile() {
  Serial.println("File name:");
  while (Serial.available() == 0) {
  }

  String fileName = Serial.readStringUntil('\n');
  Serial.println("Enter data to write to file:");
  while (Serial.available() == 0) {
  }
  String data = Serial.readStringUntil('\n');
  File file = SD.open(fileName, FILE_WRITE);
  if (file) {
    if (file.size() > 0 ) {
      file.println();
    }
    file.print(data);
    file.close();
    Serial.println("Data successfully written to file");
  } else {
    Serial.println("Error opening file");
  }
}

void readFileContent() {
  Serial.println("File name:");
  while (Serial.available() == 0) {
  }
  String fileName = Serial.readStringUntil('\n');
  File file = SD.open(fileName);
  if (file) {
    Serial.println("File contents:");
    while (file.available()) {
      Serial.write(file.read());
    }
    Serial.print("\nSize file: ");
    Serial.println(file.size());
    file.close();
  } else {
    Serial.println("Error opening file");
  }
}

void printMenu() {
  Serial.println("[1] Display a list of files on SD");
  Serial.println("[2] Delete file");
  Serial.println("[3] Create an empty file");
  Serial.println("[4] Write data to the file, from the keyboard");
  Serial.println("[5] Display the contents and size of the selected file");
}