package com.backfire.doudizhu.common;

import java.util.HashMap;

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

import com.backfire.utils.Log;


public final class AudioPool { //implements SoundPool.OnLoadCompleteListener
	private static AudioPool audioPool=new AudioPool();
	public static final int MAX_STREAMS = 10;
	private static SoundPool soundPool = null;
	private static HashMap<String, Integer> sounds = null;
	
	private AudioPool() {
		
	}
	
	public static AudioPool getInstance(){
		if(null==audioPool){
			audioPool=new AudioPool();
		}
		return audioPool;
	}
	
	public static boolean loadSoundRes(String name, Context context, int resid) {
		if (null == AudioPool.soundPool) {
			AudioPool.soundPool = new SoundPool(AudioPool.MAX_STREAMS, AudioManager.STREAM_MUSIC, 50);
			AudioPool.sounds = new HashMap<String, Integer>();
		}
		if (AudioPool.sounds.containsKey(name)) {
			Log.v("AudioPool", "name already loaded " + name);
			return false;
		}
		int id = AudioPool.soundPool.load(context, resid, 1);
		if (0 == id) {
			Log.v("AudioPool", "loadSoundRes null " + name);
			return false;
		}
		AudioPool.sounds.put(name, id);
		return true;
	}

	public static boolean freeSound(String name) {
		if (null == AudioPool.soundPool) {
			Log.v("AudioPool", "SoundPool doesn't init " + name);
			return false;
		}
		if (!AudioPool.sounds.containsKey(name)) {
			Log.v("AudioPool", "name doesn't exist " + name);
			return false;
		}
		int id = AudioPool.sounds.get(name);
		if (!AudioPool.soundPool.unload(id)) {
			Log.v("AudioPool", "unload null " + name);
		}
		AudioPool.sounds.remove(name);
		return true;
	}
	
	public static boolean playSound(Context context,String name) {
		
		if (null == AudioPool.soundPool) {
			Log.v("AudioPool", "SoundPool doesn't init " + name);
			return false;
		}
		if (!AudioPool.sounds.containsKey(name)) {
			Log.v("AudioPool", "name doesn't exist " + name);
			return false;
		}
		final AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		int streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
		int id = AudioPool.sounds.get(name);
		AudioPool.soundPool.play(id, streamVolume, streamVolume, 1, 0, 1f);
		return true;
	}
	public static void Release() {
		if (null != AudioPool.soundPool) {
			for (String key : AudioPool.sounds.keySet())
			{
				freeSound(key);
			}
			AudioPool.soundPool.release();
			AudioPool.soundPool = null;
			AudioPool.sounds.clear();
			AudioPool.sounds = null;
		}
	}
}
