package de.frajul.endlessroll.sounds;

import android.content.Context;
import android.media.MediaPlayer;

import de.frajul.endlessroll.main.ExceptionHandler;

/**
 * Created by Julian on 18.12.2015.
 */
public class Music {

    private ExceptionHandler handler;
    private MediaPlayer player;
    private boolean mute;
    private boolean paused = true;
    private int pausedPosition;

    public Music(ExceptionHandler handler, Context context, int id) {
        this.handler = handler;
        player = MediaPlayer.create(context, id);
    }

    public void setMute(boolean mute) {
        this.mute = mute;
        if (mute && !paused) {
            stop();
            paused = false;
        }
        if (!mute && !paused)
            start();
    }

    public void pause() {
        try {
            player.pause();
            paused = true;
            pausedPosition = player.getCurrentPosition();
        } catch (Exception e) {
            handler.onException(e);
        }
    }

    public void start() {
        try {
            if (!mute)
                player.start();
            paused = false;
        } catch (Exception e) {
            handler.onException(e);
        }
    }

    public void stop() {
        try {
            player.pause();
            player.seekTo(0);
            paused = true;
        } catch (Exception e) {
            handler.onException(e);
        }
    }


    public void resume() {
        try {
            if (paused) {
                player.seekTo(pausedPosition);
                start();
            }
        } catch (Exception e) {
            handler.onException(e);
        }
    }

    public MediaPlayer getPlayer() {
        return player;
    }
}
