package de.frajul.endlessroll.sounds;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import de.frajul.endlessroll.R;
import de.frajul.endlessroll.entities.tools.ToolType;
import de.frajul.endlessroll.main.GameActivity;
import de.frajul.endlessroll.main.GameLog;

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

    private Context context;
    private SoundPool soundPool;
    private boolean soundOn;

    public final Music backgroundMusic;

    public SoundManager(GameActivity activity) {
        this.context = activity;
        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);

        backgroundMusic = new Music(activity, activity, R.raw.background);
        ToolType.loadAllPlacingSounds(this);
    }

    public void setSoundOn(boolean on) {
        this.soundOn = on;
        backgroundMusic.setMute(!on);
    }

    public boolean isSoundOn() {
        return soundOn;
    }

    public void pause() {
        soundPool.autoPause();
        backgroundMusic.pause();
    }

    public void resume() {
        soundPool.autoResume();
        backgroundMusic.resume();
    }

    public void destroy() {
        backgroundMusic.getPlayer().release();
        soundPool.release();
    }

    public int loadSound(int id) {
        int sound = soundPool.load(context, id, 1);
        return sound;
    }

    public void playSound(int id) {
        float volume = getVolume();
        int feedback = soundPool.play(id, volume, volume, 1, 0, 1);
        if (feedback == 0)
            GameLog.e("SoundId: " + id + " cannot be played");
    }

    private float getVolume() {
        if (soundOn) {
            AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            float volume =
                    manager.getStreamVolume(AudioManager.STREAM_MUSIC);
            float maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            return volume / maxVolume;
        }
        return 0;
    }

}
