package
{
	import Engine.SpriteEngine;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.display.StageQuality;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.ui.Mouse;
	import flash.utils.setInterval;
	import Game.Game;

	/**
	 * ...
	 * @author KEFIR
	 */
	[Frame(factoryClass="Preloader")]
	public class Main extends Sprite
	{
		private var _lastFps:int;
		private var _fps:int;
		
		private var _frontBuffer:Bitmap;
		
		private var _Game:Game.Game = new Game.Game();
		
		private var _displayFps:TextField = new TextField();
		
		private var _dat:Date = new Date();
		
		public function Main():void
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function onEnterFrame(e:Event):void {
			
			_Game.Render();
			
			/*_displayFps.text = 'fps: ' + _lastFps + "\n" + 'sprites: ' + _Game.RenderEngine.spriteCount;
			
			_Game.RenderEngine.Buffer.draw(_displayFps);*/
			
			_fps++;
		}
		
		private function countFps():void {
			_lastFps = _fps;
			_fps = 0;
		}
		
		private function onMouseDown(e:MouseEvent):void {
			stage.focus = this;
		}

		private function init(e:Event = null):void {
			stage.quality = StageQuality.LOW;
			
			removeEventListener(Event.ADDED_TO_STAGE, init);
			setInterval(countFps, 1000);
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			
			_frontBuffer = new Bitmap(_Game.RenderEngine.Buffer);
			
			addChild(_frontBuffer);
			
			_displayFps.backgroundColor = 0xffffff;
			_displayFps.background = true;
			_displayFps.autoSize = TextFieldAutoSize.LEFT;
			
			addEventListener(KeyboardEvent.KEY_DOWN, _Game.onKeyDown);
			addEventListener(KeyboardEvent.KEY_UP, _Game.onKeyUp);
			addEventListener(MouseEvent.MOUSE_MOVE, _Game.onMouseMove );
			addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown)
			addEventListener(MouseEvent.MOUSE_DOWN, _Game.onMouseDown);
			addEventListener(MouseEvent.MOUSE_UP, _Game.onMouseUp);
			
			focusRect = false;
			
			stage.focus = this;
			
			Mouse.hide();
		}

	}

}