package engine
{
	import flash.display.DisplayObject;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Keyboard;
	
	/**
	 * ...
	 * @author Fiodar Paulavets
	 * @version 1.2
	 * @since 25.05.2012
	 */
	public class Keys 
	{
		public static const EVENT_KEY_UP: String = KeyboardEvent.KEY_UP;
		public static const EVENT_MOUSE_UP: String = MouseEvent.MOUSE_UP;
		
		private static var keys: Vector.<Boolean> = new Vector.<Boolean>(256, true);
		
		public static var mouseDown: Boolean;
		
		public static var cursor: Point = new Point();
		
		private static var _listeners: Array = new Array();
		
		public static function ProccessKeys(stage: DisplayObject): void
		{
			cursor.x = stage.mouseX;
			cursor.y = stage.mouseY;
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
		}
		
		public static function Down(key: String): Boolean
		{
			if (key.toLowerCase() == "shift") return keys[Keyboard.SHIFT];
			if (key.toLowerCase() == "ctrl") return keys[Keyboard.CONTROL];
			if (key.toLowerCase() == "space" || key == " ") return keys[Keyboard.SPACE];
			if (key.toLowerCase() == "left") return keys[Keyboard.LEFT];
			if (key.toLowerCase() == "right") return keys[Keyboard.RIGHT];
			if (key.toLowerCase() == "up") return keys[Keyboard.UP];
			if (key.toLowerCase() == "down") return keys[Keyboard.DOWN];
			if (key.toLocaleLowerCase() == "esc" || key.toLocaleLowerCase() == "escape") return keys[Keyboard.ESCAPE];
			return keys[key.toUpperCase().charCodeAt()];
		}
		
		private static function onKeyDown(e: KeyboardEvent): void
		{
			keys[e.keyCode] = true;
		}
		
		private static function onKeyUp(e: KeyboardEvent): void
		{
			keys[e.keyCode] = false;
			if (_listeners[EVENT_KEY_UP] != null)
				_listeners[EVENT_KEY_UP](e);
		}
		
		private static function onMouseDown(e: MouseEvent): void
		{
			mouseDown = true;
		}
		
		private static function onMouseUp(e: MouseEvent): void
		{
			mouseDown = false;
			if (_listeners[EVENT_MOUSE_UP] != null)
				_listeners[EVENT_MOUSE_UP](e);
		}
		
		private static function onMouseMove(e: MouseEvent): void
		{
			cursor.x = e.stageX;
			cursor.y = e.stageY;
		}
		
		/**
		 * 
		 * @param	event - строка, значение в константах
		 * @param	listener - обычная функция листенер, должна принимать переменную типа KeyboardEvent
		 */
		public static function addEventListener(event: String, listener: Function): void
		{
			_listeners[event] = listener;
		}
		
		public static function dispatchEvent(Event: String): void
		{
			_listeners[Event] = null;
			delete _listeners[Event];
		}
		
	}

}