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

String generate_api_json(bool success, String content, bool plain) {
  String json = "{\"success\": ";  // success
  json += success ? "true" : "false";
  json += ", ";
  json += "\"state\": \"";  // playing or paused?
  json += audioPlaying ? "playing" : "paused";
  json += "\"";
  if (!plain) {
    json += ", ";
    json += content;
  }
  json += "}";

  return json;
}
String generate_api_json(bool success) {  // if you just want the basic json frame with the basic info
  return generate_api_json(success, "", true);
}
String generate_api_json(bool success, String content) {  // when info is to be embedded
  return generate_api_json(success, content, false);
}


void configRoot() {
  Serial.println("[HTTP] [Config]      200 - GET '/'");

  String html = "<html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>Configuration | ";
  html += version;
  html += "</title></head><body><div style='text-align:center;'><br><br><p>Configuration of your</p><h3>NetSpeaker</h3><br><hr><br><p>Work in progress!</p></div></body></html>";

  conf_server.send(200, "text/html", html);
}

void apiRoot() {
  Serial.println("[HTTP] [API]         200 - GET '/'");

  String html = "<html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>API | ";
  html += version;
  html += "</title></head><body><div style='text-align:center;'><br><br><p>API of your</p><br><h3>NetSpeaker</h3><br><hr><br><p>Work in progress!</p></div></body></html>";

  api_server.send(200, "text/html", html);
}

void api_v1_playback_toggle() {
  Serial.println("[HTTP] [API]         200 - GET '/api/v1/playback/toggle'");

  audioPlaying = !audioPlaying;
  Serial.printf("[INFO]               Playback has switched: %s\n", audioPlaying ? "Playing" : "Paused");

  api_server.send(200, "application/json", generate_api_json(true));
}

void api_v1_playback_play() {
  Serial.println("[HTTP] [API]         200 - GET '/_api/v1/playback/play'");

  audioPlaying = true;
  Serial.printf("[INFO]               Playback has switched: Playing\n");

  api_server.send(200, "application/json", generate_api_json(true));
}

void api_v1_playback_pause() {
  Serial.println("[HTTP] [API]         200 - GET '/api/v1/playback/pause'");

  audioPlaying = false;
  Serial.printf("[INFO]               Playback has switched: Paused\n");

  api_server.send(200, "application/json", generate_api_json(true));
}

void api_v1_playback_next() {
  Serial.println("[HTTP] [API]         200 - GET '/api/v1/playback/next'");

  String songPath = nextAudio();
  String content = "\"resource_path\": \"";
  content += songPath;
  content += "\", \"resource_playlist_index\": ";
  content += String(currentPlaylistPosition);


  api_server.send(200, "application/json", generate_api_json(true, content));
}

void api_v1_playback_previous() {
  Serial.println("[HTTP] [API]         200 - GET '/api/v1/playback/previous'");

  String songPath = previousAudio();
  String content = "\"resource_path\": \"";
  content += songPath;
  content += "\", \"resource_playlist_index\": ";
  content += String(currentPlaylistPosition);

  api_server.send(200, "application/json", generate_api_json(true, content));
}

void api_v1_playback_volume() {
  String option = api_server.pathArg(0);
  bool success = true;
  Serial.printf("[HTTP] [API]         200 - GET '/api/v1/volume/%s'\n", option);

  if (option == "up") {
    currentVolume++;
    if (currentVolume > 20) currentVolume = 20;
  } else if (option == "down") {
    currentVolume--;
    if (currentVolume < 0) currentVolume = 0;
  } else if (option == "mute") {
    muted = true;
  } else if (option == "unmute") {
    muted = false;
  } else if (option == "get") {
    // just here that no 'success: false' is sent
  } else if (option == "0") {
    currentVolume = 0;
  } else if (option == "1") {
    currentVolume = 1;
  } else if (option == "2") {
    currentVolume = 2;
  } else if (option == "3") {
    currentVolume = 3;
  } else if (option == "4") {
    currentVolume = 4;
  } else if (option == "5") {
    currentVolume = 5;
  } else if (option == "6") {
    currentVolume = 6;
  } else if (option == "7") {
    currentVolume = 7;
  } else if (option == "8") {
    currentVolume = 8;
  } else if (option == "9") {
    currentVolume = 9;
  } else if (option == "10") {
    currentVolume = 10;
  } else if (option == "11") {
    currentVolume = 11;
  } else if (option == "12") {
    currentVolume = 12;
  } else if (option == "13") {
    currentVolume = 13;
  } else if (option == "14") {
    currentVolume = 14;
  } else if (option == "15") {
    currentVolume = 15;
  } else if (option == "16") {
    currentVolume = 16;
  } else if (option == "17") {
    currentVolume = 17;
  } else if (option == "18") {
    currentVolume = 18;
  } else if (option == "19") {
    currentVolume = 19;
  } else if (option == "20") {
    currentVolume = 20;
  } else {
    success = false;
  }

  if (!muted) audio.setVolume(currentVolume);  // set volume if not muted
  else audio.setVolume(0);                     // if muted, set volume to 0

  String content = "\"volume\": ";  // prepare the http response
  content += String(currentVolume);
  content += ", \"muted\": ";
  content += muted ? "true" : "false";
  api_server.send(200, "application/json", generate_api_json(success, content));  // generate json and send it
}

void api_v1_playback_info() {
  Serial.println("[HTTP] [API]         200 - GET '/api/v1/playback/info'");
  String content = "\"resource_path\": \"" + pbInfo.resourcePath + "\", ";       // resource's path
  content += "\"resource_type\": \"" + pbInfo.type + "\", ";                     // type
  content += "\"resource_title\": \"" + pbInfo.title + "\", ";                   // title
  content += "\"resource_album\": \"" + pbInfo.album + "\", ";                   // album
  content += "\"resource_artist\": \"" + pbInfo.artist + "\", ";                 // artist
  content += "\"resource_track\": \"" + pbInfo.track + "\", ";                   // track
  content += "\"resource_year\": \"" + pbInfo.year + "\", ";                     // year
  content += "\"resource_genre\": \"" + pbInfo.genre + "\", ";                   // genre
  content += "\"resource_copyright\": \"" + pbInfo.copyright + "\", ";           // copyright
  content += "\"resource_playlist_path\": \"" + currentPlaylist + "\", ";        // playlist path
  content += "\"resource_playlist_index\": " + String(currentPlaylistPosition);  // playlist index (starting from 0)

  api_server.send(200, "application/json", generate_api_json(true, content));
}

void api_v1_playlist_get() {
  Serial.println("[HTTP] [API]         200 - GET '/api/v1/playlist/get'");

  int index = 0;
  String content = "\"playlist\": {";
  String currentSong;
  bool firstRun = true;

  while (true) {
    currentSong = getSongFromPlaylist(currentPlaylist, index);
    if (currentSong == "") {
      content += "\"";
      break;
    } else if (!firstRun) {
      content += "\", ";
    }
    content += "\"" + String(index);
    content += "\": \"";
    content += currentSong;
    firstRun = false;

    index++;
  }
  content += "}";

  api_server.send(200, "application/json", generate_api_json(true, content));
}

void api_v1_playlist_create() {
  Serial.println("[HTTP] [API]         200 - POST '/api/v1/playlist/create'");

  // get the right POST param
  String folderPath;
  for (int i = 0; i < api_server.args(); i++) {
    if (api_server.argName(i) == "folderPath") {
      folderPath = api_server.arg(i);
      break;
    }
  }

  bool code = createPlaylistFromDirectory(folderPath);
  if (code) {  // if creating the playlist was successful
    String playlistPath = folderPath + "/" + directoryPlaylistName + playlistExtension;
    String content = "\"playlist_path\": \"" + playlistPath + "\"";
    api_server.send(200, "application/json", generate_api_json(true, content));
  } else {
    api_server.send(200, "application/json", generate_api_json(false));
  }
}

void api_v1_playlist_play() {
  Serial.println("[HTTP] [API]         200 - POST '/api/v1/playlist/play'");

  // get the right POST param
  String playlistPath;
  for (int i = 0; i < api_server.args(); i++) {
    if (api_server.argName(i) == "playlistPath") {
      playlistPath = api_server.arg(i);
      break;
    }
  }

  if (getSongFromPlaylist(playlistPath, 0) == "") {                      // if playlist is empty or nonexistent
    api_server.send(200, "application/json", generate_api_json(false));  // send no success info
  } else {
    currentPlaylist = playlistPath;
    currentPlaylistPosition = -1;
    nextAudio();
    api_server.send(200, "application/json", generate_api_json(true));  // just return the success info
  }
}

void api_v1_settings_restart() {
  SD.end();           // delete SD object and sync its cache to flash
  WiFi.disconnect();  // disconnect wifi
  Serial.printf("[INFO]               Restarting after 5000ms.\n", waitOnSDCardEject, retrySDMountTreshold);
  delay(5000);
  api_server.send(200, "application/json", "{\"restart\": true, \"wait_time\": 5000}");
  ESP.restart();  // reset everything and restart the program
}

void setupConfigWeb() {
  if (runConfServer) {
    conf_server.onNotFound([]() {
      Serial.println("[HTTP] [Config]      404: Not Found");
      conf_server.send(404, "text/html", "<html><head><title>Not Found</title></head><body><h1>Not Found</h1><p>This resource does not exist on this server.</p></body></html>");
    });
    conf_server.on("/", configRoot);

    Serial.println("[HTTP] [Config]      Starting config server (http) on port " + String(webport_config));
    conf_server.begin();
    Serial.println("[HTTP] [Config]      Started Config server");
  }
}

void setupApiWeb() {
  api_server.onNotFound([]() {
    Serial.println("[HTTP] [API]         404: Not Found");
    api_server.send(404, "application/json", "{\"code\": 404, \"message\": \"Resource not found.\"}");
  });
  api_server.on("/", apiRoot);
  api_server.on("/api/v1/playback/toggle", HTTP_GET, api_v1_playback_toggle);
  api_server.on("/api/v1/playback/play", HTTP_GET, api_v1_playback_play);
  api_server.on("/api/v1/playback/pause", HTTP_GET, api_v1_playback_pause);
  api_server.on("/api/v1/playback/next", HTTP_GET, api_v1_playback_next);
  api_server.on("/api/v1/playback/previous", HTTP_GET, api_v1_playback_previous);
  api_server.on("/api/v1/playback/info", HTTP_GET, api_v1_playback_info);
  api_server.on("/api/v1/playlist/get", HTTP_GET, api_v1_playlist_get);
  api_server.on("/api/v1/playlist/create", HTTP_POST, api_v1_playlist_create);
  api_server.on("/api/v1/playlist/play", HTTP_POST, api_v1_playlist_play);
  api_server.on(UriBraces("/api/v1/volume/{}"), HTTP_GET, api_v1_playback_volume);
  api_server.on("/api/v1/settings/restart", HTTP_GET, api_v1_settings_restart);

  Serial.println("[HTTP] [API]         Starting API server (http) on port " + String(webport_api));
  api_server.begin();
  Serial.println("[HTTP] [API]         Started config server");
}

void loopServer() {
  api_server.handleClient();
  if (runConfServer) conf_server.handleClient();
}