/*
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/

int setupSD(int SD_CS, int SPI_MISO, int SPI_MOSI, int SPI_SCK) {
  pinMode(SD_CS, OUTPUT);
  digitalWrite(SD_CS, HIGH);               // make microSD-card reader board listen to the ESP (over SPI)
  SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI);  // start SPI
  int ret = SD.begin(SD_CS);
  if (ret == 1) Serial.printf("[SETUP]              Set up SD card successfully (Pins: MISO %d | MOSI %d | SCK %d | CS %d)\n", SPI_MISO, SPI_MOSI, SPI_SCK, SD_CS);
  return ret;  // returns 1 if everything is OK, 0 if an error occured (eg. wiring not correct)
}

String getWiFiSSID(String confPath) {
  String ssid;
  char new_char;

  if (!SD.exists(confPath)) return "";  // if the config file doesn't exist, return nothing and exit
  File confFile = SD.open(confPath);

  ssid = (char)confFile.read();
  while (ssid[ssid.length() - 1] != '\n' && confFile.available()) {
    new_char = (char)confFile.read();
    if (new_char == '\n') break;
    ssid += new_char;
  }

  return ssid;
}
String getWiFiSSID() {
  return getWiFiSSID(wifiConfigPath);
}

String getWiFiPSK(String confPath) {
  String line1;
  String psk;
  char new_char;

  if (!SD.exists(confPath)) return "";  // if the config file doesn't exist, return nothing and exit
  File confFile = SD.open(confPath);

  // skip the first line
  line1 = (char)confFile.read();                                                                     // read character...
  while (line1[line1.length() - 1] != '\n' && confFile.available()) line1 += (char)confFile.read();  // ... as long as a newline hits

  psk = (char)confFile.read();
  while (confFile.available()) {
    new_char = (char)confFile.read();
    if (new_char == '\n') break;
    psk += new_char;
  }

  return psk;
}
String getWiFiPSK() {
  return getWiFiPSK(wifiConfigPath);
}

bool createPlaylistFromDirectory(String folderpath) {  // create a .m3u playlist from all directory contents (the directory 'folderpath' is used)
  File folder;
  File playlist;

  if (folderpath[folderpath.length() - 1] == '/' && folderpath.length() > 1) {  // check if file is ending with a "/" - because it wont work otherwise
    Serial.printf("[ERROR]              Can't use a folder path with trailing /\n");
    return false;
  }

  if (SD.exists(folderpath)) {  // only open if the folder exists,
    folder = SD.open(folderpath);
  } else {  // ...else print error and exit function (with return false)
    Serial.printf("[ERROR]              Can't open \"%s\" because it doesn't exist!\n", folderpath.c_str());
    return false;
  }
  playlist = SD.open(folderpath + "/" + directoryPlaylistName + playlistExtension, FILE_WRITE);  // open a (new) playlist file

  while (true) {
    File entry = folder.openNextFile();
    if (!entry) break;                                                                                                // end the while(true) when no files left!
    if (!entry.isDirectory() && String(entry.name()) != String(directoryPlaylistName + playlistExtension).c_str()) {  // only if not a directory or the playlist itself
      playlist.println(folderpath + "/" + String(entry.name()));
    }
  }
  playlist.flush();  // write changes to sd card

  return true;
}

String getSongFromPlaylist(String path, int position) {
  String song;
  File playlist;
  char currentChar;
  int currentPosition = 0;

  if (!SD.exists(path) or SD.open(path).isDirectory()) {
    Serial.printf("[ERROR]              Can't open \"%s\" because it either doesn't exist or is a directory!\n", path.c_str());
    return "";
  }
  playlist = SD.open(path);

  while (playlist.available()) {
    if (currentPosition == position) {                                                                // if the right position is reached
      song = (char)playlist.read();                                                                   // read character...
      while (song[song.length() - 1] != '\n' && playlist.available()) song += (char)playlist.read();  // ... as long as a newline hits
      song = song.c_str();
      song[song.length() - 1] = '\0';  // remove the trailing '\n'
      song = String(song);
      return song;  // return the result
    }
    currentChar = playlist.read();                              // read character...
    while (currentChar != '\n') currentChar = playlist.read();  // ... as long as a newline hits
    currentPosition++;
  }

  return song;  // return an empty string if out of index or whatever
}