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 started;
    private boolean muted;
    private boolean paused;
    private boolean activityPaused;

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

    public void start() {
        started = true;
        paused = false;
        onStateChanged();
    }

    public void stop() {
        started = false;
        onStateChanged();
        reset();
    }

    public void setMuted(boolean muted) {
        this.muted = muted;
        onStateChanged();
    }

    public void pause() {
        paused = true;
        onStateChanged();
    }

    public void activityPause() {
        activityPaused = true;
        onStateChanged();
    }

    public void activityResume() {
        activityPaused = false;
        onStateChanged();
    }

    private void onStateChanged() {
        try {
            boolean newState = started && !muted && !paused && !activityPaused;
            if (player.isPlaying()) {
                if (!newState)
                    player.pause();
            } else {
                if (newState)
                    player.start();
            }
        } catch (Exception e) {
            handler.onException(e);
        }
    }

    public void reset() {
        try {
            player.seekTo(0);
        } catch (Exception e) {
            handler.onException(e);
        }
    }

    public MediaPlayer getPlayer() {
        return player;
    }
}
