#include "SerialMP3Player.h"
#include <ESP8266WiFi.h>

#define TX D3
#define RX D2
#define BUTTON D1

#define STARTED_STRING "Status: playing"
#define STOPPED_STRING "Status: stopped"
#define MAX_PLAYTIME 60000

unsigned long lastpressed = 0;
unsigned long pressed_cycles = 0;
unsigned long lastreleased = 0;
const unsigned long wait_until_next_pressed = 100;

SerialMP3Player mp3(RX,TX);

bool button_pressed(unsigned int button_pin){
  static bool buttons_state = false;
  if(millis() - lastpressed > wait_until_next_pressed)
  {
    if(digitalRead(button_pin) == LOW)
    {
      pressed_cycles++;
      lastpressed = millis();
      buttons_state = true;
    }
    else{
      pressed_cycles = 0;
      lastreleased = millis();
      buttons_state = false;
    }
  }
  return(buttons_state);
}

void setup() {

  Serial.begin(115200);     // start serial interface
  pinMode(BUTTON,INPUT_PULLUP);

  WiFi.mode(WIFI_OFF);
  WiFi.forceSleepBegin();
  delay(10);

  mp3.begin(9600);        // start mp3-communication
  delay(500);             // wait for init


  mp3.setVol(25);
  delay(500);
  
  mp3.sendCommand(CMD_SEL_DEV, 0, 2);   //select sd-card
  delay(500);             // wait for init
 
}

// the loop function runs over and over again forever
unsigned long started_plying = 0;
bool playing = false;
void loop() {
  
 
  if(true == button_pressed(BUTTON))
  {
    playing = false;
    mp3.play(1);
    started_plying = millis(); 
    Serial.println("");          
    Serial.println("Song playing started!");
    while((playing == false) && (millis()-started_plying < MAX_PLAYTIME))
    {
      delay(100);
      mp3.qStatus();
      if (mp3.available()){
        String answer = mp3.decodeMP3Answer();
        if(answer.indexOf(STARTED_STRING) > -1)
        {
          playing = true;
          Serial.println("Song started!");
        }
      }
    }

    while((playing == true) && (millis()-started_plying < MAX_PLAYTIME))
    {
      delay(100);
      mp3.qStatus();
      if (mp3.available()){
        String answer = mp3.decodeMP3Answer();
        if(answer.indexOf(STOPPED_STRING) > -1)
        {
          playing = false;
          Serial.println("Song finished!");
        }

      }
    }

    if(playing == true)
      mp3.stop();
    Serial.println("Song playing done!");

    while(true == button_pressed(BUTTON))
    {
        delay(100);
    }
  }
}