package {
	import com.bit101.components.InputSlidernew;
	import com.bit101.components.PushButton;
	import com.bit101.components.VBox;
	import com.greensock.TweenLite;
	import com.netgrind.core.Key;
	import com.netgrind.core.Utils;
	import adobe.utils.CustomActions;
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import nape.callbacks.CbType;
	import nape.geom.Vec2;
	import nape.phys.Body;
	import nape.phys.BodyType;
	import nape.space.Space;
	import nape.util.BitmapDebug;
	import flash.ui.Keyboard;
	import com.netgrind.core.UtilsArt
	import com.netgrind.core.Scheduler;
	
	/**
	 * ...
	 * @author netgrind
	 */
	public class Level extends Sprite {
		
		[Embed(source = "../lib/Map.png")]public var map:Class;
		[Embed(source = "../lib/buildings/building_repairshop.png")]public var repairTex:Class;
		public static var i:Level;
		public static var offset:Point = new Point();
		public static var wallCollisionType:CbType = new CbType();
		public static var carCollisionType:CbType = new CbType();
		
		private var _space:Space;
		private var body:Body;
		private var debug:BitmapDebug;
		private var car:Car;
		
		private var targetWaypoint:Waypoint;
		private var background:Bitmap;
		private var text:TextWindow;
		private var dialogCallback:Function;
		private var missionLoader:MissionLoader;
		private var repair:Sprite;
		private var countdown:Countdown;
		private var endScreen:EndScreen;
		public var timer:MissionTimer;
		public var mirror:Mirror;
		public var bg:Sprite;
		
		public var hudTarget:HUDTarget;
		public var slowdownFilter:Sprite;
		public var time:Number = 1;
		
		public function Level() {
			super();
			i = this;
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			CharacterManager.setup();
			
			_space = new Space(new Vec2(0, 0));
			_space.worldLinearDrag = 1;
			_space.worldAngularDrag = 0.8;
			body = new Body(BodyType.KINEMATIC);
			body.space = _space;
			body.cbTypes.add(wallCollisionType);
			
			bg = new Sprite();
			addChild(bg);
			
			background = new map();
			background.smoothing = true;
			bg.addChild(background);
			
			debug = new BitmapDebug(600,400,0x66333333,true);
			Main.debugLayer.addChild(debug.display);
			
			bg.addChild(new LoadManager(body));
			car = new Car(_space, new Vec2(1950,2345));
			
			var raceManager:RaceManager = new RaceManager(car,this);
			bg.addChild(raceManager);			
			bg.addChild(car);
			
			repair = new Sprite();
			var r:Bitmap = new repairTex();
			repair.addChild(r);
			r.x = -r.width * .5;
			r.y = -r.height * .5;
			var rp:Waypoint = Waypoint.getFromName("wRepairShop1");
			repair.x = rp.x;
			repair.y = rp.y;
			bg.addChild(repair);
			
			//HUD CREATION
			hudTarget = new HUDTarget();
			addChild(hudTarget);
			hudTarget.x = 300;
			hudTarget.y = 200;
			
			slowdownFilter = UtilsArt.makeRectangle(600, 400, 0xffffff, .5);
			addChild(slowdownFilter);
			
			timer = new MissionTimer();
			addChild(timer);
			
			text = new TextWindow();
			addChild(text);
			
			Scheduler.invokeEvery(update);	
			
			missionLoader = new MissionLoader();
			
			mirror = new Mirror();
			addChild(mirror);
			mirror.x = 300 - mirror.width * 0.5;
			mirror.addChar(0);
			
			countdown = new Countdown();
			addChild(countdown);
			countdown.x = 300;
			countdown.y = 200;
			
			endScreen = new EndScreen();
			addChild(endScreen);
			
			Key.bindFunctionToKeyPress(startMission, Keyboard.NUMBER_1, "SM01");
			Key.bindFunctionToKeyPress(startMission, Keyboard.NUMBER_2, "SM03");
			Key.bindFunctionToKeyPress(startMission, Keyboard.NUMBER_3, "SM07A");
		}
		
		public function startMission(missionName:String):void {
			var storyMission:Mission = missionLoader.createMission(missionName);
			storyMission.activate(car, this);
		}
		
		public function startRace(raceName:String, callback:Function):void {
			var mission:Mission = missionLoader.createMission(raceName, foo);
			function foo():void {
				if (callback != null) callback();
				endScreen.show(mission);
				pause();
				Key.bindFunctionToKeyHold(postEndScreen,Keyboard.SPACE);
			}
			car.body.velocity.setxy(0, 0);
			car.pause =  true;
			car.body.position = mission.points[0].waypoint.position;
			car.updatePosition();
			car.cameraTarget.setTo(car.x, car.y);
			countdown.start(function():void {
				car.pause = false;
				mission.activate(car, Level.i);
			});
		}
		
		private function postEndScreen():void {
			endScreen.hide();
			unpause();
		}
		
		public function setTargetWaypoint(waypoint:Waypoint = null):void {
			hudTarget.addPoint(waypoint.position);
		}
		
		public function pause(time:Number = .5 ):void {
			TweenLite.to(this, time, { time:0 } );
		}
		public function unpause(time:Number = .5 ):void {
			TweenLite.to(this, time, { time:1 } );
			if (dialogCallback != null) {
				dialogCallback();
				dialogCallback = null;
			}
		}
		
		public function update():void {
			Scheduler.timeScale = time;
			var step:Number = Scheduler.deltaMS / 1000 * Scheduler.timeScale;
			if(step!=0)_space.step(step);
			slowdownFilter.alpha = 1 - Scheduler.timeScale;
			
			bg.x = Utils.lerp(bg.x,(stage.stageWidth * .5) - car.cameraTarget.x,.1);
			bg.y = Utils.lerp(bg.y, (stage.stageHeight * .5) - car.cameraTarget.y, .1);
			offset.x = bg.x;
			offset.y = bg.y;
			hudTarget.center.setxy( -offset.x + 300, -offset.y + 200);	
			car.updatePosition();
			
			scaleX = scaleY = 1;
			
			if (!car.pause&&Utils.getDistance(car, repair) < 50) {
				car.repair();
			}
			
			if (Main.debug) {
				Main.debugLayer.x = bg.x;
				Main.debugLayer.y = bg.y;
				Main.debugLayer.scaleX = Main.debugLayer.scaleY = scaleX;
				debug.transform.tx = bg.x;
				debug.transform.ty = bg.y;
				debug.display.x = -bg.x;
				debug.display.y = -bg.y;
				debug.clear();
				debug.draw(_space);
				debug.flush();
			}
		}
		
		public function displayDialog(dia:Vector.<TextChunk>, callback:Function, character:Character):void {
			if (dia.length != 0) {
				dialogCallback = callback;
				pause();
				text.displayDialog (dia, character, unpause);
			}else {
				callback();
			}
		}
		
		public function endMission(mission:Mission):void {
			
		}
	}
	
}