package {
	import flash.display.*;
	import flash.events.*;
	import flash.ui.*;
	import com.elbowchocolates.*;

	public class KeyboardTest extends MovieClip {
		private const ROWS:int = 5;
		private const COLS:int = 9;
		private const OFFSET_X:int = 30;
		private const OFFSET_Y:int = 23;
		private const SPACER:int = 11;

		private var characters:Vector.<MovieClip> = new Vector.<MovieClip>();
		private var index:int;
		private var cursor:MovieClip = new Cursor();

		public function KeyboardTest():void {
			init();
		}

		private function init():void {
			stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
			cursor.x = OFFSET_X;
			cursor.y = OFFSET_Y;
			addChild(cursor);

		}

		private function handleKeyDown(event:KeyboardEvent):void {
			if (event.keyCode >= 65 && event.keyCode <= 90 && characters.length < (ROWS * COLS)) {
				type(String.fromCharCode(event.keyCode));
			} else if (event.keyCode == Keyboard.BACKSPACE || event.keyCode == Keyboard.DELETE) {
				backspace();
			} else if (event.keyCode == Keyboard.SPACE) {
				type(" ");
			} else if (event.keyCode == Keyboard.ENTER && characters.length < (COLS * (ROWS-1))) {
				newLine();
			}
		}

		private function moveCursor():void {
			var cursorIndex:int = characters.length;
			if (cursorIndex < (COLS * ROWS)) {
				cursor.visible = true;
				cursor.x = (cursorIndex % COLS) * (80 + SPACER) + OFFSET_X;
				cursor.y = Math.floor(cursorIndex / COLS) * (81 + SPACER) + OFFSET_Y;
			} else {
				cursor.visible = false;
			}
		}

		private function type(letter:String):void {
			var character:MovieClip = new Chocolate(letter,characters.length);
			index = characters.length;
			var nextIndex:int = index + 1;
			character.x = (index % COLS) * (80 + SPACER) + OFFSET_X;
			character.y = Math.floor(index / COLS) * (81 + SPACER) + OFFSET_Y;
			characters.push(character);
			addChild(character);
			moveCursor();
		}

		private function backspace():void {
			if (characters.length > 0) {
				removeChild(characters[characters.length-1]);
				characters.splice(characters.length-1,1);
				moveCursor();
			}
		}

		private function newLine():void {
			var remainder:int = COLS - (characters.length % COLS);
			for (var i:int = 0; i<remainder; i++) {
				var blank:MovieClip = new MovieClip();
				characters.push(blank);
				addChild(blank);
			}
			moveCursor();
		}
	}
}