package classes.matuto.midia {
	
	
	import flash.display.Stage;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
		
	/**
	* ...
	* @author Default
	*/
	final public class KeyBoardManager {
		
		private static var _rootStage		:Stage;
		private static var _commands_obj	:Object = new Object();
		private static var _dispatcher		:EventDispatcher = new EventDispatcher();
		
		public static function init( rootStage :Stage ) :void
		{
			if(!_rootStage)
			{
				_rootStage = rootStage;
				
				Key.initialize(_rootStage);
				
				rootStage.addEventListener( KeyboardEvent.KEY_DOWN, key_down_handle );
				rootStage.addEventListener( KeyboardEvent.KEY_UP, key_up_handle );
			}
		}
		
		
		public static function addCommand( id :String, commands :Array, filter :Array = null, repeat :Boolean = false, call :Function = null, ...arguments ) :void
		{		
			_commands_obj[id] = { commands:commands, filter:filter, call:call, repeat:repeat, params:arguments, enabled:true };	
		}
		
		
		public static function removeCommand(id :String) :void
		{
			if(_commands_obj[id]) delete _commands_obj[id];
		}
		
		public static function executeCommand(id :String) :void
		{
			var info :Object = _commands_obj[id];
			
			if (info)
			{
				var params	:*			= info.params;
				var call 	:Function 	= info.call;
				
				if(call!=null) call.apply(null, params);
			}
		}		
		
		private static function key_down_handle( event :KeyboardEvent ) :void
		{
			
			var key :uint = event.keyCode;
			
			for(var i :String in _commands_obj){
				
				var info :Object = _commands_obj[i];
				
				var commands 	:Array 		= info.commands;
				var filter		:Array		= info.filter;
				var call 	 	:Function 	= info.call;
				var repeat		:Boolean	= info.repeat;
				var params		:*			= info.params;
				var enabled		:Boolean	= info.enabled;
				
				if( (_rootStage.focus is TextField) && !(filter && (filter.indexOf(_rootStage.focus)!=-1) ) ) continue;
				
				if(enabled)
				{
					var keys_down :Boolean = true;
					
					for(var j :int=0; j<commands.length; j++){
						var _key :int = commands[j];
						if(!Key.isDown(_key)) keys_down = false;
					}
					
					if(keys_down)
					{
						if(call!=null) call.apply(null, params);
						info.enabled = repeat;
					}
				}
				
			}
			
		}
		
		
		private static function key_up_handle(event :KeyboardEvent) :void
		{
			
			var key :uint = event.keyCode;
			
			for(var i :String in _commands_obj){
				
				var info :Object = _commands_obj[i];
				
				var commands 	:Array 		= info.commands;
				var enabled		:Boolean	= info.enabled;
				
				if(commands.indexOf(key)!=-1 && !enabled) {
					info.enabled = true;
					//break;
				}
				
			}
			
		}		
		
	}
	
}