//--------------------------------------------------------------------------------------------------
// GameMediaLibrary
//--------------------------------------------------------------------------------------------------

package  {
	import adobe.utils.CustomActions;	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Vector3D;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	/**	
	 * @author Santiago Rosas
	 */
	public class GameMediaLibrary extends EventDispatcher {		
				
		private var _mediaFiles:Dictionary; //of (String, Object) (Media files by name)
		private var _numSWFsLoaded:int = 0;
		private var _numSWFsToLoad:int;
		private var _loadedListener:Function;

		public function GameMediaLibrary(swfNames:Vector.<String>, loadedListener:Function) 
		{						
			_numSWFsToLoad = swfNames.length;
			_loadedListener = loadedListener;
			
			_mediaFiles = new Dictionary();	
			
			for each (var swfName:String in swfNames) {
				var loader:Loader = new Loader();
				loader.load(new URLRequest(swfName + ".swf"));
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWFLoaded);
			}
			
			addEventListener(Event.COMPLETE, loadedListener);						
		}

		
		private function onSWFLoaded(event:Event):void 
		{		
			var loader:Loader = (event.target as LoaderInfo).loader;
			
			var mediaMC:MovieClip = loader.getChildAt(0) as MovieClip;
			
			for (var i:int = 0; i < mediaMC.numChildren; i++) {	
				var symbol:Object = mediaMC.getChildAt(i);
				var className:String = symbol.toString();			
				var symbolName:String = className.split("[object m_")[1];
				
				if (symbolName != null) {				
					symbolName = symbolName.replace("]", "");	
					_mediaFiles[symbolName] = symbol;										
				}
			}
			
			_numSWFsLoaded++;			
			
			if (_numSWFsLoaded == _numSWFsToLoad) {			
				_loadedListener.call();
			}
		}		
		
		
		public function getSymbol(aName:String):Object {
			if (!(aName in _mediaFiles)) {
				throw new Error("Media file " + aName + " isn't in the library.");				
			} else {
				return _mediaFiles[aName];
			}
		}
		
		
		public function getSprite(name:String):Sprite 
		{
			var vClass:Class = Object(getSymbol(name)).constructor;
			return new vClass() as Sprite;			
		}
		
		
		public function getMovieClip(name:String):MovieClip
		{
			var vClass:Class = Object(getSymbol(name)).constructor;
			return new vClass() as MovieClip;			
		}
		
		
		public function getSimpleButton(name:String):SimpleButton
		{
			var vClass:Class = Object(getSymbol(name)).constructor;
			return new vClass() as SimpleButton;			
		}		
		
		
		public function setSprite(sprite:Sprite, name:String):void 
		{
			_mediaFiles[name] = sprite;
		}
		
		
	}
	
}