package com.guru.project.brother.game.coreStep
{
	import adobe.utils.CustomActions;
	import com.guru.call.FunctionCall;
	import com.guru.call.ICall;
	import com.guru.component.timer.CountDownTimer;
	import com.guru.display.graphicDigit.GraphicDigitGroup;
	import com.guru.display.LabelMovieClip;
	import com.guru.facebookApplicationBase.gameBase.GameStepBase;
	import com.guru.facebookApplicationBase.tracking.Tracking;
	import com.guru.panel.PanelBase;
	import com.guru.project.brother.footer.Footer;
	import com.guru.project.brother.game.GameDataObject;
	import com.guru.project.brother.game.item.GiftItem;
	import com.guru.utils.TimerUtil;
	import flash.display.MovieClip;
	import fl.motion.MatrixTransformer;
	import fl.motion.easing.Linear;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.ui.Keyboard;
	import flash.ui.Mouse;
	/**
	 * ...
	 * @author Eddy Lee
	 */
	public class GameSectionCoreStep extends GameStepBase
	{
		var current=0;
		var blueRotCenter:Point;
		var blueMat;
		var line_array = new Array();
		var i=0;
		var start_x;
		var start_y;
		var end_x=0;
		var end_y=0;
		var adjacant = 0;
		var preAngle = 0;
		var line_count = 0;
		var point:Point;
		var prevrotation = 0;
		var mouseDown:Boolean = false;
		var checkpoint0_passed:Boolean = false;
		var checkpoint1_passed:Boolean = false;
		var checkpoint2_passed:Boolean = false;
		var checkpoint3_passed:Boolean = false;
		var checkpoint4_passed:Boolean = false;
		var sew_machine_head_mc:LabelMovieClip;
		var start_hint_mc:LabelMovieClip;
		var pin_blur_mc:LabelMovieClip;
		var gameStarted:Boolean = false;
		var count_down_timer:CountDownTimer;
		var mGraphicDigitGroup1:GraphicDigitGroup;
		var score:Number;
		var line_color:Number = 2;
		var line_data:String = "";
		var road_array:Array;
		var road_score_array:Array = new Array();
		var center_x;
		var center_y;
		
		private var mGameEnd_bol:Boolean = false;
		private var mLineCount_num:Number = 0;
		
		private var mGiftItem:GiftItem;
		private var mGameEndPanel:PanelBase;
		
		public function GameSectionCoreStep(pTimeline_mc:MovieClip, pNextCall:ICall = null, pPrevCall:ICall = null, pData_obj:Object = null)
		{
			if(Footer.getInstance())
				Footer.getInstance().hide();
			
			super(pTimeline_mc, pNextCall, pPrevCall, pData_obj);
			
			Tracking.getInstance().track("GameSection_CoreStep");
			
			mGiftItem = new GiftItem(mTimeline_mc.canvas_mc.item_mc, true);
			mGiftItem.loadClipArtList(GameDataObject.sClipArt_array);
			mGiftItem.changeFabricTo(GameDataObject.sFabric_num, null, true);
			mGiftItem.changeItemTo(GameDataObject.sItemID_num, new FunctionCall(this, init));
		}
		
		private function init():void
		{
			line_color = GameDataObject.sItemID_num + 1;
			
			//center_x = mTimeline_mc.canvas_mc.item_mc.center_mc.x;
			//center_y = mTimeline_mc.canvas_mc.item_mc.center_mc.y;
			
			center_x = mTimeline_mc.pin_mc.x;
			center_y = mTimeline_mc.pin_mc.y;
			
			start_x=center_x;
			start_y=center_y;
			blueRotCenter=new Point(center_x,center_y);
			point = new Point(center_x,center_y);
			
			road_score_array[0] = 20;
			road_score_array[1] = 5;
			road_score_array[2] = 1;
			road_score_array[3] = 0;
			road_score_array[4] = 0;
			road_score_array[5] = 0;
			
			//mTimeline_mc.canvas_mc.x = mTimeline_mc.pin_mc.x + mTimeline_mc.canvas_mc.item_mc.center_mc.x + mTimeline_mc.canvas_mc.x;
			//mTimeline_mc.canvas_mc.y = mTimeline_mc.pin_mc.y + mTimeline_mc.canvas_mc.item_mc.center_mc.y + mTimeline_mc.canvas_mc.y;
			
			mGiftItem.getComponentTimeline().center_mc.visible = true;
			
			mTimeline_mc.canvas_mc.x = mTimeline_mc.pin_mc.x - mGiftItem.getComponentTimeline().center_mc.x * mGiftItem.getTimeline().scaleX * mGiftItem.getComponentTimeline().scaleX;
			mTimeline_mc.canvas_mc.y = mTimeline_mc.pin_mc.y - mGiftItem.getComponentTimeline().center_mc.y * mGiftItem.getTimeline().scaleY * mGiftItem.getComponentTimeline().scaleY;
			//mTimeline_mc.canvas_mc.rotation = -mGiftItem.getComponentTimeline().center_mc.rotation;
			
			mGraphicDigitGroup1 = new GraphicDigitGroup(mTimeline_mc.graphicDigitGroup1_mc);
			mGraphicDigitGroup1.setNumber(0, null, GraphicDigitGroup.JUMP_MODE);
			
			start_hint_mc = new LabelMovieClip(mTimeline_mc.start_hint_mc,'start');
			count_down_timer = new CountDownTimer(mTimeline_mc.count_down_mc);
			count_down_timer.setTime(120);
			blueMat=mTimeline_mc.canvas_mc.transform.matrix.clone();
			sew_machine_head_mc = new LabelMovieClip(mTimeline_mc.sewing_machine_head, 'start');
			pin_blur_mc = new LabelMovieClip(mTimeline_mc.pin_mc.pin_blur_mc, 'start');
			
			
			mTimeline_mc.pin_mc.line_mc1.gotoAndStop(line_color);
			mTimeline_mc.pin_mc.line_mc2.gotoAndStop(line_color);
			mTimeline_mc.pin_mc.line_mc3.gotoAndStop(line_color);
			mTimeline_mc.pin_mc.line_mc4.gotoAndStop(line_color);
			mTimeline_mc.pin_mc.line_mc5.gotoAndStop(line_color);
			
			road_array = new Array();
			
			var clip_mc:MovieClip;
			for (var i:Number = 0; clip_mc = mGiftItem.getComponentTimeline().road_mc["road_" + i + "_mc"]; i++ )
			{
				road_array.push(clip_mc);
			}
			
			
			score = 0;
			
			mGameEndPanel = new PanelBase("", mTimeline_mc.gameEndPanel_mc);
		}
		
		override protected function onFadeInDone(pDoneCall:ICall = null):void 
		{
			
			super.onFadeInDone(pDoneCall);
			
			Mouse.hide();
			
			mTimeline_mc.stage.addEventListener(MouseEvent.MOUSE_DOWN, setMouseDown);
			mTimeline_mc.stage.addEventListener(MouseEvent.MOUSE_UP, setMouseUp);
			
			mTimeline_mc.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
			mTimeline_mc.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyboardUP);
			mTimeline_mc.addEventListener(Event.ENTER_FRAME, EnterFrame);
			
			count_down_timer.setTimeUpCall(new FunctionCall(this, onTimeUp));
			
		}
		function step1():void
		{
			
		}

		function step2():void
		{
		}
		
		private function onTimeUp():void
		{
			this.onGameDone(false);
		}
		
		function setMouseDown(e) 
		{
			mouseDown = true;
		}
		
		function setMouseUp(e) 
		{
			mouseDown = false;
			
		}
		
		function rotateBlue(deg:Number):void {
			
			var mat:Matrix= blueMat.clone();
			
			MatrixTransformer.rotateAroundExternalPoint(mat,blueRotCenter.x,blueRotCenter.y,deg);
			
			mTimeline_mc.canvas_mc.transform.matrix=mat;
			
		}
		
		function onKeyboardUP(event):void
		{
			sew_machine_head_mc.playTo('end');
			pin_blur_mc.playTo('end');
		}
		
		function onKeyboardDown(event):void
		{
			if(event.keyCode == Keyboard.SPACE)
			{
				sew_machine_head_mc.playTo('hold');
				pin_blur_mc.playTo('hold');
				if (gameStarted == false) {
					mGiftItem.getComponentTimeline().center_mc.visible = false;
					count_down_timer.start();
					start_hint_mc.playTo('end');
					gameStarted = true;
				}
				
				i++;
				mTimeline_mc.pin_mc.gotoAndStop(i);
				if (i == 5) {
					var lineaContructor:Class = mGiftItem.getComponentTimeline().line_mc.constructor;
					var linea = new lineaContructor();
					linea.gotoAndStop(line_color);
					line_count++;
					mTimeline_mc.line_count.text = line_count;
					line_array.push(linea);
					
					
					
					
					//adjacant=Math.sqrt(((canvas_mc.x-400)*(canvas_mc.x-400))+((canvas_mc.y-200)*(canvas_mc.y-200)));
					//trace(adjacant);
					
					
					var target=mTimeline_mc.canvas_mc;
					
					var p3 = mGiftItem.getComponentTimeline().globalToLocal(new Point(point.x, point.y));
					var p2 = mTimeline_mc.canvas_mc.globalToLocal(new Point(point.x,point.y));//

					
					linea.x = p2.x;
					linea.y = p2.y;
					
					
					linea.rotation=-1*mTimeline_mc.canvas_mc.rotation;
					start_x=mTimeline_mc.canvas_mc.x;
					start_y=mTimeline_mc.canvas_mc.y;
					
					line_data+=''+Math.round(p3.x)+','+Math.round(p3.y)+','+Math.round(linea.rotation)+'/';
					
					mTimeline_mc.canvas_mc.addChild(linea);
					
					if (!checkpoint0_passed && HitTest.complexHitTestObject(linea, mGiftItem.getComponentTimeline().road_mc.checkpoint_0_mc, 10))
					{
						checkpoint0_passed = true;	
						trace('Pass 0');
					}
					if (checkpoint0_passed && !checkpoint1_passed && (HitTest.complexHitTestObject(linea, mGiftItem.getComponentTimeline().road_mc.checkpoint_1_mc, 10)))
					{
						checkpoint1_passed = true;	
						trace('Pass 1');
					}
					if (checkpoint1_passed && !checkpoint2_passed && (HitTest.complexHitTestObject(linea, mGiftItem.getComponentTimeline().road_mc.checkpoint_2_mc, 10)))
					{
						checkpoint2_passed = true;
						trace('Pass 2');
					}
					if (checkpoint2_passed && !checkpoint3_passed && (HitTest.complexHitTestObject(linea, mGiftItem.getComponentTimeline().road_mc.checkpoint_3_mc, 10)))
					{
						checkpoint3_passed = true;	
						trace('Pass 3');
					}
					if (checkpoint3_passed && !checkpoint4_passed && (HitTest.complexHitTestObject(linea, mGiftItem.getComponentTimeline().road_mc.checkpoint_4_mc, 10)))
					{
						checkpoint4_passed = true;	
						count_down_timer.stop();
						this.onGameDone(true);
						return;
					}
					
					mLineCount_num++;
					
					var ontheroad = false;
					for (var j = 0; j<road_array.length; j++ ) {
						if (HitTest.complexHitTestObject(linea, road_array[j], 10)) {
							ontheroad = true;
							trace("score added: "+road_score_array[j]);
							score += road_score_array[j];
							break;
						}
					}
					if (ontheroad == false ) {
						trace("off the road");
						this.onGameDone(false);
						return;	
					}
					
					/*
					if (HitTest.complexHitTestObject(linea, mTimeline_mc.canvas_mc.road_mc.great_mc, 10)) {
						trace('great');
						score += 5;
						//linea.good_phase_mc.play();
					}else {
						if (HitTest.complexHitTestObject(linea, mTimeline_mc.canvas_mc.road_mc.good_mc, 10)) {
							trace('good');
							score += 3;
							
						}else {
							if (HitTest.complexHitTestObject(linea, mTimeline_mc.canvas_mc.road_mc.poor_mc, 10)) {
								trace('poor');
								score += 1;
								//linea.great_phase_mc.play();
							}else {
								this.onGameDone(false);
								return;
								
							}
							
						}
						
					}
					*/
					mGraphicDigitGroup1.setNumber(score, new FunctionCall(this, step1), GraphicDigitGroup.FAST_MODE);

					
					i=0;
				}
				
				mTimeline_mc.canvas_mc.y-=2;
				current=0;
				blueMat=mTimeline_mc.canvas_mc.transform.matrix.clone();
			}
			
		}
		
		function EnterFrame(event) {
			//trace(event.buttonDown);
			mTimeline_mc.hand_mc.x = mTimeline_mc.stage.mouseX;
			mTimeline_mc.hand_mc.y = mTimeline_mc.stage.mouseY;
			
			
			
			
			var adjside = mTimeline_mc.stage.mouseX-center_x;
			var oppside = -1*(mTimeline_mc.stage.mouseY-center_y);
			var angle = Math.atan2(oppside, adjside); // in radians
			angle = Math.round(angle / Math.PI * 180); // convert to degrees
			
			if (angle<0) {
				angle = 360 + angle;
			}
			
			angle = angle * -1;
			
			
			
			
			
			var currentMouseY = mTimeline_mc.stage.mouseY;
			if (mouseDown==true) {
				mTimeline_mc.hand_mc.gotoAndStop(2);
				current+=angle-preAngle
				
			}else {
				mTimeline_mc.hand_mc.gotoAndStop(1);
			}
			preAngle = angle;
			
	
			rotateBlue(current);
		}
		
		private function onGameDone3(pWin_bol:Boolean):void
		{
			Logger.alex("onGameDone3");
			//Logger.alex("NUMBER OF LINE: " + mLineCount_num);
			
			if (mNextStepCall)
				mNextStepCall.execute(null, { win:pWin_bol} );
		}
		
		private function onGameDone2(pWin_bol:Boolean):void
		{
			Logger.alex("onGameDone2");
			TimerUtil.setFrameDelay(60, new FunctionCall(this, onGameDone3, pWin_bol));
		}
		
		private function onGameDone(pWin_bol:Boolean):void
		{
			Logger.alex("onGameDone");
			if (!mGameEnd_bol)
			{
				mGameEnd_bol = true;
				this.stop();
				
				GameDataObject.sNumberOfLine_num = mLineCount_num;
				
				GameDataObject.sScoreGot_num = score;
				
				if(pWin_bol)
					GameDataObject.sTimeLeft_num = count_down_timer.getTime();
				else
					GameDataObject.sTimeLeft_num = 0;
				
				if(pWin_bol)
					mGameEndPanel.getContent().gotoAndStop(2);
					
				mGameEndPanel.showPanel(new FunctionCall(this, onGameDone2, pWin_bol));
			}
		}
		
		override public function dispose():void 
		{
			if(Footer.getInstance())
				Footer.getInstance().show();
			
			if (line_data.charAt(line_data.length - 1) == "/")
				line_data = line_data.substr(0, line_data.length - 1);
				
			GameDataObject.sLine_str = line_data;
			
			this.stop();
			
			mGameEndPanel.dispose();
			mGraphicDigitGroup1.dispose();
			start_hint_mc.dispose();
			count_down_timer.dispose();
			
			for (var i = 0; i<line_array.length; i++ ) {
				
				mTimeline_mc.canvas_mc.removeChild(line_array[i]);
				
			}
			
			//trace('4');
			
			super.dispose();
			//trace('5');
		}
		
		public function stop():void
		{
			
			
			//trace('123');
			mTimeline_mc.stage.removeEventListener(MouseEvent.MOUSE_DOWN, setMouseDown);
			mTimeline_mc.stage.removeEventListener(MouseEvent.MOUSE_UP, setMouseUp);
			
			mTimeline_mc.stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
			mTimeline_mc.stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyboardUP);
			mTimeline_mc.removeEventListener(Event.ENTER_FRAME, EnterFrame);
			
		
			//trace('2');
			
			
			sew_machine_head_mc.playTo('start');
			pin_blur_mc.playTo('start');
			
			//mGraphicDigitGroup1.
			start_hint_mc.stop();
			count_down_timer.stop();
			
			//mGraphicDigitGroup1.dispose();
			//
			//start_hint_mc.dispose();
			//count_down_timer.dispose();
			
		//	sew_machine_head_mc.dispose();
			//pin_blur_mc.dispose();
			
			//trace('3');
			
			
			Mouse.show();
		}
		
	}

}