package com.backfire.doudizhu.common;

import java.util.HashMap;
import java.util.Map;

import net.yeeyo.doudizhu.feiyu.R;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import com.backfire.room.data.ConfigCenter;
import com.backfire.utils.Log;

public class LobbySoundManager {
	private String TAG = LobbySoundManager.class.getName();

	private byte[] sync = new byte[0];
	private boolean binit = false;
	private SoundPool soundPool = null;
	private Map<String, Integer> soundMap = null;

	public void init() {
		synchronized (sync) {
			if (binit)
				return;
			binit = true;
			soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 100);
			soundMap = new HashMap<String, Integer>();
			loadSound();
		}
	}

	public void loadSound() {
		try {
			// 加载共用音效
			soundMap.put("button_press",
					soundPool.load(DdzApplication.getApplication(), R.raw.button_press, 0));
			
			soundMap.put("success_music",
					soundPool.load(DdzApplication.getApplication(), R.raw.success_music, 0));
		} catch (Exception e) {
			Log.e(this, e);
		}
	}

	public void play(String key) {
		synchronized (sync) {
			if (soundMap == null) {
				clear();
				init();
			}
			if (!soundMap.containsKey(key)) {
				return;
			}
			int id = soundMap.get(key);
			if (DdzApplication.getApplication().isDebug()) {
				Log.i(this, "Play-" + key + "-" + id);
			}
			if (soundPool != null && !ConfigCenter.volume_off) {
				AudioManager mAudioManager = (AudioManager) DdzApplication
						.getApplication().getSystemService(
								Context.AUDIO_SERVICE);
				float max = mAudioManager
						.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
				float current = mAudioManager
						.getStreamVolume(AudioManager.STREAM_MUSIC);
				int voice_music = ShareData.getInstance().getIntValue(
						"MUSIC_VOICE", (int) ((current / max) * 100f));
				soundPool.setVolume(soundPool.play(id, 1, 1, 1, 0, 1f),
						voice_music / 100f, voice_music / 100f);
			}
		}
	}

	public void clear() {
		synchronized (sync) {
			if (binit) {
				binit = false;
				soundMap.clear();
				soundPool.release();
				soundPool = null;
			}
		}
	}
}

