/*
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/>
*/

#include "WiFi.h"       // https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi/src
#include "Audio.h"      // https://github.com/schreibfaul1/ESP32-audioI2S
#include "SPI.h"        // https://github.com/espressif/arduino-esp32/tree/master/libraries/SPI/src
#include "SD.h"         // https://github.com/espressif/arduino-esp32/tree/master/libraries/SD/src
#include "FS.h"         // https://github.com/espressif/arduino-esp32/tree/master/libraries/FS/src
#include <WebServer.h>  // https://github.com/espressif/arduino-esp32/tree/master/libraries/WebServer


// define all constants
const String version = "NetSpeaker v0.1.1-dev";     // version string used e.g. for access point ssid when wifi couldn't connect
const int operation_mode = 0;                       // 0: standalone (no wifi; no api); 1: interconnected (no buttons, but api and wifi)
const int SD_CS = 5;                                // BOARD SPECIFIC
const int SPI_MISO = 19;                            // BOARD SPECIFIC
const int SPI_MOSI = 23;                            // BOARD SPECIFIC
const int SPI_SCK = 18;                             // BOARD SPECIFIC
const int I2S_DOUT = 2;                             // can be changed on need
const int I2S_BLCK = 4;                             // can be changed on need
const int I2S_LRC = 15;                             // can be changed on need
const int sdCardEjectPin = 13;                      // pin which is used to tell the program to eject the sd card (so that the file system doesn't brake)
const int audioVolumePin = 25;                      // pin where the poti is connected to (wired as voltage divider)
const int pausePlaybackPin = 12;                    // switch (the switching is done digitally, a button has to be connected, NO switch) between play and pause
const int forwardButtonPin = 14;                    // pin for forward button
const int backwardButtonPin = 27;                   // pin for backward btn
const int waitOnSDCardEject = 5000;                 // defines how long to wait (in ms) after the button for SD card eject was pressed (on pin 'sdCardEjectPin'!)
const int retrySDMountTreshold = 1000;              // defines how long to wait (in ms) to the next try of mounting the sd card
const int readyPin = 32;                            // for an LED that shows if everything started up correctly (SD card mounted, wifi connected, ...)
const int webport_config = 8080;                    // port for the configuration interface
const int webport_api = 80;                         // port for the api (can't be the same as 'webport_config', will throw an error)
const bool runConfServer = true;                    // variable if the config server should be setup and run
const String playlistExtension = ".m3u";            // extension for playlist files
const String directoryPlaylistName = ".directory";  // name for directory playlists (not a path, just a filename without ext.!)
const String wifiConfigPath = "/.wifi.conf";        // MAX LENGTH: 32 resp. 63 chars; path to configuration file; content: <WiFi SSID>\n<WiFi PSK> (ssid and password divided by an newline)
const String apSSID = version;                      // ssid of access point opened when not able to connect to wifi
const String apPSK = "aA16161Aa";                   // pre-shared-key of access point opened when not able to connect to wifi

// create all needed variables
int currentVolume = 21;                                                          // variable where current volume (0...21) is stored
String currentSongPath;                                                          // path to currently playing song
bool audioPlaying = true;                                                       // play song or not?
Audio audio;                                                                     // Audio object (for playing audio, decoding mp3, ...)
int currentPlaylistPosition = 0;                                                 // the current position in the current playlist
String currentPlaylist = "/audio/" + directoryPlaylistName + playlistExtension;  // path to current playlist
int currentWiFiMode = 0;                                                         // DON'T CHANGE IF NOT KNOWING WHAT YOU'RE DOING; selector for wether an AP (1) should be set up or a wifi (0) should be connected
bool apON = false;                                                               // DON'T CHANGE IF NOT KNOWING WHAT YOU'RE DOING; is the access point opened?
WebServer conf_server(webport_config);                                           // web server for configuration (e.g. WiFi password setting)
WebServer api_server(webport_api);                                               // web server for api (e.g. pause/play)


void setup() {
  Serial.begin(115200);  // setup Serial console (over USB) with baud 115200

  // connect to sd card reader
  Serial.println("[SETUP]              Setting up SD-Card reader");
  while (!setupSD(SD_CS, SPI_MISO, SPI_MOSI, SPI_SCK)) {
    Serial.printf("[SETUP]              Can't connect to SD card reader! Waiting for %d milliseconds...\n", retrySDMountTreshold);
    delay(retrySDMountTreshold);
  }

  if(operation_mode == 0) {  // things only need to be done if in interconnected mode
    setupWiFi();
    setupConfigWeb();
    setupApiWeb();
  } else if (operation_mode == 1) {  // things only need to be done if in standalone mode
    // setup all pins (not SPI and other buses!)
    pinMode(sdCardEjectPin, INPUT);
    pinMode(backwardButtonPin, INPUT);
    pinMode(pausePlaybackPin, INPUT);
    pinMode(forwardButtonPin, INPUT);
    pinMode(readyPin, OUTPUT);
  } else {
    Serial.println("[FATAL] PLEASE CHOOSE A OPERATION MODE! VALID OPTIONS: 0; 1. SLEEPING FOREVER.");
    while(true) delay(100);
  }

  setupAudio();                           // setup audio library
  createPlaylistFromDirectory("/audio");  // create playlist from default dir ("/audio")
  audio.connecttoFS(SD, getSongFromPlaylist(currentPlaylist, currentPlaylistPosition).c_str());  // play first element of the playlist
  digitalWrite(readyPin, HIGH);                                                                  // show that startup is done and everything works fine
}
void loop() {
    if(operation_mode == 0) {  // things only need to be done if in interconnected mode
    setupWiFi();  // if connection was lost
    if(audioPlaying) audio.loop();  // play audio if not paused
    if(esp_timer_get_time()%100 == 0) {  // REALLY NEEDED; audio playing won't work else!
      loopServer();  // listen on http ports all 100 ms 
    }
  }

  if(operation_mode == 1) {  // things only need to be done if in standalone mode
    if(audioPlaying) audio.loop();  // play audio if not paused

    loopBtnListeners();

    // for SD card eject
    if (analogRead(sdCardEjectPin) > 4000) {  // bigger than 4000: so that it's not affected by a little touch of fingers (4095 is maximum; 0 minimum)
      SD.end();                               // delete SD object and sync its cache to flash
      digitalWrite(readyPin, LOW);            // indicate that SD card can get removed (the ready-LED will go off)
      Serial.printf("[SETUP]              Unmounting SD-Card, waiting for %dms and trying to remount (every %d milliseconds)...\n", waitOnSDCardEject, retrySDMountTreshold);
      delay(waitOnSDCardEject);
      ESP.restart();  // reset everything and restart the program
    }
  }
}
