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

void setupAudio() {
  audio.setPinout(I2S_BLCK, I2S_LRC, I2S_DOUT);  // tell the audio library what output pins to use
  Serial.printf("[SETUP]              Set up audio card successfully (Pins: BLCK %d | LRC %d | DOUT %d)\n", I2S_BLCK, I2S_LRC, I2S_DOUT);
}

void nextAudio() {
  String songPath;

  currentPlaylistPosition++;  // increment once
  songPath = getSongFromPlaylist(currentPlaylist, currentPlaylistPosition);
  if(songPath == "") {  // if the end of the playlist is reached go to start
    currentPlaylistPosition = -1;  // the next time "nextAudio()" is called it will increment to 0
    nextAudio();  // recursive call
    return;  // exit
  }
  Serial.printf("[INFO]               Starting next audio from playlist (ID: %d, Path: %s)\n", currentPlaylistPosition, songPath.c_str());
  audio.connecttoFS(SD, songPath.c_str());  // play the next song
  
  delay(100);  // button has to be pressed for at least 0.1s!
  while(analogRead(pausePlaybackPin) > 4000) {}  // wait until btn is released
}

void previousAudio() {
  String songPath;

  currentPlaylistPosition--;
  if(currentPlaylistPosition < 0) currentPlaylistPosition = 0;

  songPath = getSongFromPlaylist(currentPlaylist, currentPlaylistPosition);
  Serial.printf("[INFO]               Starting previous audio from playlist (ID: %d, Path: %s)\n", currentPlaylistPosition, songPath.c_str());
  audio.connecttoFS(SD, songPath.c_str());  // play the previous song
  
  delay(100);  // button has to be pressed for at least 0.1s!
  while(analogRead(pausePlaybackPin) > 4000) {}  // wait until btn is released
}

void switchPlaybackIfButtonClicked() {
  if(analogRead(pausePlaybackPin) > 4000) {  // check if btn was clicked
    audioPlaying = !audioPlaying;  // play if paused, pause if playing
    Serial.printf("[INFO]               Playback has switched: %s\n", audioPlaying ? "Playing" : "Paused");
    delay(100);  // button has to be pressed for at least 0.1s!
    while(analogRead(pausePlaybackPin) > 4000) {}  // wait until btn is released
  }
}

void forwardButtonHandler() {
  if(analogRead(forwardButtonPin) > 4000) {
    nextAudio();  // play next audio file from playlist
  }
}

void backwardButtonHandler() {
  if(analogRead(backwardButtonPin) > 4000) {
    previousAudio();  // play previous audio file from playlist
  }
}

void setAudioVolume() {
  int newCurrentVolume = analogRead(audioVolumePin) / 195;  // read voltage from audioVolumePin and divide by 195 (min. volume is 0, max. 21; 21 fits 195 times into 4095 (maximum input))
  if(currentVolume != newCurrentVolume) {  // just do it if the volume changed
    currentVolume = newCurrentVolume;
    audio.setVolume(currentVolume);  // set volume
    Serial.printf("[INFO]               Set volume to %d/21!\n", currentVolume);
  }
}

void loopBtnListeners() {
  // some thing for pausing etc.
  switchPlaybackIfButtonClicked();  // pause/play if wanted
  forwardButtonHandler();  // handle clicks on forward button
  backwardButtonHandler();  // handle clicks on backward button
  setAudioVolume();  // set audio volume
}


void audio_eof_mp3(const char *info){  // MUST HAVE THIS NAME (audio_eof_mp3) because it's a callback function for the Audio.h library
  Serial.printf("[Audio.h] EOF_MP3    %s\n", info);
  nextAudio();
}
void audio_eof_speech(const char *info){
  Serial.printf("[Audio.h] EOF_Speech %s\n", info);
}
void audio_info(const char *info){
  Serial.printf("[Audio.h] Info       %s\n", info);
}
void audio_id3data(const char *info){  //id3 metadata
  Serial.printf("[Audio.h] ID3Data    %s\n", info);
}
void audio_showstation(const char *info){
  Serial.printf("[Audio.h] Station    %s\n", info);
}
void audio_showstreamtitle(const char *info){
  Serial.printf("[Audio.h] StreamTitle %s\n", info);
}
void audio_bitrate(const char *info){
  Serial.printf("[Audio.h] Bitrate    %s\n", info);
}
void audio_commercial(const char *info){            // duration of ad in sec
  Serial.printf("[Audio.h] Commercial %s\n", info);
}
void audio_icyurl(const char *info){                // Name of radio station
  Serial.printf("[Audio.h] IcyURL     %s\n", info);
}
void audio_lasthost(const char *info){              // stream URL played
  Serial.printf("[Audio.h] Lasthost   %s\n", info);
}