package gen2wave.rp70biodemo.msrocr;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.util.Log;

import java.io.IOException;

import gen2wave.rp70biodemo.R;

/**
 * Manages beeps and vibrations.
 */
public final class BeepManager {

	private static final String TAG = "BeepManager";

	private static final float BEEP_VOLUME = 1.0f;
	private static final long VIBRATE_DURATION = 250;

	private final Context mContext;
	private MediaPlayer mMediaPlayer;
	private SharedPreferences mPref;
	private int sound = 0;

	public BeepManager(Context ctx, int soundtype) {
		mContext = ctx;
		if(soundtype == 0)
            sound= R.raw.adara;
        else if(soundtype == 1)
            sound=R.raw.aldebaran;
		mMediaPlayer = buildMediaPlayer(ctx);
		mPref = PreferenceManager.getDefaultSharedPreferences(ctx);
	}
	public BeepManager(Context ctx, int soundtype, int data) {
		mContext = ctx;
		sound=soundtype;
		mMediaPlayer = buildMediaPlayer(ctx);
		mPref = PreferenceManager.getDefaultSharedPreferences(ctx);
		 
	}

	public void playBeepSoundAndVibrate(int soundtype) {
		/*if (mPref.getBoolean(Settings.PREF_BEEP, Settings.PREF_BEEP_DEF)
				&& mMediaPlayer != null) {*/
	       
			mMediaPlayer.start();
		//}
		/*if (mPref.getBoolean(Settings.PREF_VIBRATE, Settings.PREF_VIBRATE_DEF)) {
			Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}*/
	}

	private MediaPlayer buildMediaPlayer(Context activity) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);      
        /* When the beep has finished playing, rewind to queue up another one. */
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer player) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                player.seekTo(0);
            }
        });

        AssetFileDescriptor file = activity.getResources().openRawResourceFd(sound);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            file.close();
            mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayer.prepare();
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            mediaPlayer = null;
        }
        return mediaPlayer;
    }

	@Override
	protected void finalize() throws Throwable {
		if (mMediaPlayer != null)
			mMediaPlayer.release();
		super.finalize();
	}
}
