package vandy.mooc.utils;

import java.io.IOException;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class ParcelableCommandMusicAsync
       extends ParcelableCommandMusic 
       implements MediaPlayer.OnPreparedListener {
    /**
     * Debugging tag used by the Android logger.
     */
    private static String TAG = 
        ParcelableCommandMusicAsync.class.getSimpleName();

    /**
     * A UID generated by Eclipse for serialization purposes.
     */
    private static final long serialVersionUID = 11L;

    /**
     * MediaPlayer that will play the requested song.
     */
    MediaPlayer mPlayer;

    /**
     * Keep track of whether a song is currently playing.
     */
    private static boolean mSongPlaying;

    /**
     * Constructor.
     */
    public ParcelableCommandMusicAsync() {
        super();
    }

    /**
     * Execute the command to play a song.
     */
    public void execute(Context context,
                        Bundle args) {
        if (mSongPlaying) 
            // Stop playing the current song.
            stopSong();

        if (mPlayer == null)
            // Create a MediaPlayer that will play the requested song(s).
            mPlayer = new MediaPlayer();

        // Indicate the MediaPlayer will stream the audio.
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        // Get the song to play.
        final Uri songUri = args.getParcelable(SONG_URI);

        try {
            // Indicate the Uri for the song to play.
            mPlayer.setDataSource(songUri.toString());

            // Register "this" as the callback when the designated
            // song is ready to play.
            mPlayer.setOnPreparedListener(this);

            // This call doesn't block the UI Thread.
            mPlayer.prepareAsync(); 
        } catch (IOException e) {
        	e.printStackTrace();
        }
    }

    /** 
     * Called back when MediaPlayer is ready to play the song.
     */
    public void onPrepared(MediaPlayer player) {
        Log.i(TAG,"onPrepared() entered");

        // Just play the song once, rather than have it loop
        // endlessly.
        player.setLooping(false);

        // Note that song is now playing.
        mSongPlaying = true;

        // Start playing the song.
        player.start();
    }

    /**
     * Unexecute the command to stop playing a song.
     */
    public void unexecute(Context context) {
        stopSong();
    }

    /**
     * Stops the MediaPlayer from playing the song.
     */
    private void stopSong() {
        Log.i(TAG,"stopSong() entered");

        // Stop playing the song.
        mPlayer.stop();
        
        // Reset the state machine of the MediaPlayer.
        mPlayer.reset();

        // Note that no song is playing.
        mSongPlaying = false;
    }
}
