#include "mbed.h"
#include "player.h"


InterruptIn KEY_PS(D5);             //Play/Stop/Recording
InterruptIn KEY_Pre(D6);           //Previous
InterruptIn KEY_Next(D4);          //Next
InterruptIn KEY_Up(D3);            //Volume up
InterruptIn KEY_Down(D7);          //Volume dowm

DigitalOut MyLED(D8);          //LED

Player player;
Ticker t;
Timer timer;

extern char list[15][14];            //song list
extern unsigned char vlume;     //vlume
extern unsigned char vlumeflag; //set vlume flag
extern char index;              //song play index
extern char index_MAX;          //how many song in all
extern playerStatetype  playerState;

int falltime;

void LEDflip()
{  
    if (playerState == PS_PAUSE) MyLED = 0;
	else if (playerState == PS_STOP) MyLED = 0;
	else MyLED = !MyLED;
}

void fallFlip()
{
    falltime=timer.read_ms();
}

void riseFlip()
{
    if((timer.read_ms()-falltime)>1000)    //1s
    {
        playerState = PS_RECORDING;        //long press for recording
    }
    else
    {
        if(playerState == PS_PAUSE)playerState = PS_PLAY;       //play or pause
        else playerState = PS_PAUSE; 
    }   
}


void VolumeFlip()
{
    if(KEY_Up == 0)
    {
       vlume = (vlume-0x10 >= 0)?vlume-0x10:vlume;
    }
    
    if(KEY_Down == 0)
    {
        vlume = (vlume+0x10<0xA0)?vlume+0x10:vlume;
    }
    printf("vlume : %d\r\n",10-vlume/0x10);
    vlumeflag = 1;
}


void Pre_Next()
{
    if(KEY_Next == 0)
    {
        index = (index+1 > index_MAX)?0:index+1;
    }
    
    if(KEY_Pre == 0)
    {
        index = (index-1 < 0)?index_MAX:index-1;
    }
    playerState = PS_STOP; 
}

int main() {
    
    KEY_PS.fall(&fallFlip);
    KEY_PS.rise(&riseFlip);
    KEY_Up.fall(&VolumeFlip);
    KEY_Down.fall(&VolumeFlip);
    KEY_Pre.fall(&Pre_Next);
    KEY_Next.fall(&Pre_Next);
    t.attach(&LEDflip,0.5);
    
    player.begin();
    timer.start();

    while(1)
    {
        player.playFile(list[index]); 
        if(playerState == PS_RECORDING)
        {
           player.recordFile("/recording.WAV");
           player.playFile("/recording.WAV"); 
        }          
    }

}


