package  
{	
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.geom.Point;	
	import flash.ui.Keyboard;
	import flash.utils.Dictionary;
	
	/**
	 * ...
	 * @author Santiago Rosas
	 */
	public class KeyInput
	{
		private var _isDownKeyDown:Boolean;
		private var _isUpKeyDown:Boolean;
		private var _isLeftKeyDown:Boolean;
		private var _isRightKeyDown:Boolean;
		private var _isSpaceKeyDown:Boolean;
		private var speed:Point;
		private var listeners:Dictionary; //of (uint, Function) Key listeners by key code
		
		
		public function KeyInput()
		{			
			Main.instance.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			Main.instance.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			Main.instance.stage.focus = Main.instance.stage;
			speed = new Point(0, 0);
			
			listeners = new Dictionary();
		}
		
		
		public function onDeactivate():void 
		{
			_isUpKeyDown = false;
			_isDownKeyDown = false;
			_isLeftKeyDown = false;
			_isRightKeyDown = false;
		}
		
		
		private function onKeyDown(e:KeyboardEvent):void 
		{
			if (e.keyCode == Keyboard.S || e.keyCode == Keyboard.DOWN) {
				_isDownKeyDown = true;
			}
			else if (e.keyCode == Keyboard.W || e.keyCode == Keyboard.UP) {
				_isUpKeyDown = true;
			}
			else if (e.keyCode == Keyboard.A || e.keyCode == Keyboard.LEFT) {
				_isLeftKeyDown = true;
			}
			else if (e.keyCode == Keyboard.D || e.keyCode == Keyboard.RIGHT) {
				_isRightKeyDown = true;
			}
			else if (e.keyCode == Keyboard.SPACE) {
				_isSpaceKeyDown = true;
				if (Main.instance.player != null && !Main.instance.isGameOver()) {
					Main.instance.player.onSpaceKeyDown();
				}
			}			
	
			/*
			if (listeners[e.keyCode] != null) {				
				listeners[e.keyCode]();
			}
			*/
			
		}
		
		
		private function onKeyUp(e:KeyboardEvent):void 
		{
			if (e.keyCode == Keyboard.S || e.keyCode == Keyboard.DOWN) {
				_isDownKeyDown = false;
			}
			else if (e.keyCode == Keyboard.W || e.keyCode == Keyboard.UP) {
				_isUpKeyDown = false;
			}
			else if (e.keyCode == Keyboard.A || e.keyCode == Keyboard.LEFT) {
				_isLeftKeyDown = false;
			}
			else if (e.keyCode == Keyboard.D || e.keyCode == Keyboard.RIGHT) {
				_isRightKeyDown = false;
			}			
			else if (e.keyCode == Keyboard.SPACE) {
				_isSpaceKeyDown = false;										
			}
			//Cheats
			
			/*
			else if (e.keyCode == Keyboard.NUMBER_1) {
				Main.instance.cheatBeatLevel();
			}
			*/
		}
		
		
		public function get isDownKeyDown():Boolean
		{
			return _isDownKeyDown;
		}
		

		public function get isUpKeyDown():Boolean
		{
			return _isUpKeyDown;
		}
		
		
		public function get isLeftKeyDown():Boolean
		{
			return _isLeftKeyDown;
		}		
		
		
		public function get isRightKeyDown():Boolean
		{
			return _isRightKeyDown;
		}		
		
		
		public function get isSpaceKeyDown():Boolean
		{
			return _isSpaceKeyDown;
		}
		
	}

}