package  
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	/**
	 * ...
	 * @author beisik
	 */
	public class Sounds 
	{
		[Embed(source = '../lib/sounds/up_buy.mp3')] private const embedDamaged: Class;
		[Embed(source = '../lib/sounds/boom.mp3')] private const embedExplosion: Class;
		[Embed(source = "../lib/sounds/up_buy.mp3")] private const embedWin: Class;
		[Embed(source = "../lib/sounds/music2.mp3")] private const embedProp: Class;
		
		public static var manager: Sounds;
		
		private var channels: Vector.<SoundChannel>;
		private var sounds: Array;
		private var transforms: Array;
		
		private const MAX_CHANNELS: uint = 15;
		
		public function Sounds() 
		{
			channels = new Vector.<SoundChannel>();
			
			sounds = [];
			sounds['damaged'] = new embedDamaged();
			sounds['explosion'] = new embedExplosion();
			sounds['win'] = new embedWin();
			sounds['prop'] = new embedProp();
			
			transforms = [];
			transforms['explosion'] = new SoundTransform(1.0);
			transforms['prop'] = new SoundTransform(0.5);
		}
		
		public function playSound(soundName: String): void
		{
			var sound: Sound = sounds[soundName];
			if (!sound) return;
			
			// если уже максимум каналов, то не воспроизводим (либо удаляем какой-нибудь)
			if (channels.length >= MAX_CHANNELS) return;
			
			var transform: SoundTransform = transforms[soundName];
			
			if (soundName == "prop")
				channel = sound.play(0, int.MAX_VALUE, transform);
			else
				var channel: SoundChannel = sound.play(0, 0, transform);
			channels.push(channel);
			channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
		}
		
		private function onSoundComplete(e: Event): void
		{
			var channel: SoundChannel = e.target as SoundChannel;
			channel.removeEventListener(Event.SOUND_COMPLETE, onSoundComplete);
			channels.splice(channels.indexOf(channel, 0), 1);
		}
		
	}

}