package ui.parts
{
	import com.google.analytics.debug.Label;
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.display.Bitmap;
	import flash.display.Graphics;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.NativeProcessExitEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.net.FileReference;
	import flash.net.Socket;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;

	import blocks.Block;
	
	import cc.makeblock.mimicar.uiwidgets.DeviceDebug;
	import cc.makeblock.util.FileUtil;
	import cc.makeblock.util.HexUtil;
	import cc.makeblock.mbot.util.PopupUtil;
	import extensions.ArduinoManager;
	import extensions.SerialManager;
	
	import org.aswing.JLabel;
	import org.aswing.event.AWEvent;
	import org.aswing.geom.IntRectangle;
	
	import scratch.ScratchObj;
	import scratch.ScratchSprite;
	import scratch.ScratchStage;
	
	import translation.Translator;
	
	import ui.BlockPalette;
	import ui.PaletteSelector;
	
	import uiwidgets.Button;
	import uiwidgets.DialogBox;
	import uiwidgets.IconButton;
	import uiwidgets.IndicatorLight;
	import uiwidgets.ScriptsPane;
	import uiwidgets.ScrollFrame;
	import uiwidgets.SimpleTooltips;
	import uiwidgets.TextPane;
	import uiwidgets.ZoomWidget;
	
	import util.ApplicationManager;
	import util.JSON;
	import util.ReadStream;
	public class MIQMeum extends UIPart
	{
		private var shape:Shape;
		private var button1:IconButton;
		private var button2:IconButton;
		private var button3:IconButton;
		private var button4:IconButton;
		private var button5:IconButton;
		private var button6:IconButton;
		private var button7:IconButton;
		private var button8:IconButton;
		private var SerialPortNumber:String;
		private var icon_b1:IconButton;
		private var icon_b2:IconButton;
		private var icon_b3:IconButton;
		private var icon_b4:IconButton;
		static private var panel:DeviceDebug;
		private var DeviceMode:int = 0;
		private var DEVICES_MODE_NO_DEVICE:int = 0;
		private var DEVICES_MODE_BOOTLOADER:int = 1;
		private var DEVICES_MODE_WORK:int = 2;
		private var DEVICES_MODE_DEBUG:int = 3;
		private var DEVICES_MODE_ENTER_DEBUG:int = 4;
		private var CheckStatus:int = 0;
		private var CHECK_STATUS_NULL:int = 0;
		private var CHECK_STATUS_READY_UPLOAD:int = 1;
		private var CHECK_STATUS_UPLOADING:int = 2;
		private var CHECK_STATUS_UPLOAD_END:int = 3;
		private var CHECK_STATUS_LOAD_DEBUG:int = 4;
		private var CHECK_STATUS_SERIAL_CONNECTED:int = 5;
		private var CHECK_STATUS_DEBUG:int = 6;
		private var CHECK_STATUS_KEEP_AUDIO_MAX_VALUE:int = 7;
		private var CHECK_STATUS_END:int = 8;
		private var CHECK_STATUS_ENTER_DEBUG:int = 9;
		private var CHECK_STATUS_EXIT_DEBUG:int = 10;
		private var CHECK_STATUS_OPEN_AUDIO_MAX_VALUE_SWITCH:int = 11;
		private var CHECK_STATUS_CLOSE_AUDIO_MAX_VALUE_SWITCH:int = 12;
		private var indicator:IndicatorLight;
		private var label_test:JLabel = null;//遮罩层

		public function MIQMeum(app:IQCar)
		{
			this.app = app;

			addChild(shape = new Shape());

			button1 = new IconButton(letsmove, 'meumbutton1');
			button1.x = 20;
			button1.y = 10;
			button1.width = 50;
			button1.height = 50;		
			addChild(button1);
			SimpleTooltips.add(button1, {text: "Let's move", direction: 'bottom'});

			button2 = new IconButton(download, 'meumbutton2');
			button2.x = button1.x + button1.width + 20;
			button2.y = 10;
			button2.width = 50;
			button2.height = 50;		
			addChild(button2);
			SimpleTooltips.add(button2, {text: "USB", direction: 'bottom'});

			button3 = new IconButton(deletepj, 'meumbutton3');
			button3.x = button2.x + button2.width + 20;
			button3.y = 10;
			button3.width = 50;
			button3.height = 50;		
			addChild(button3);
			SimpleTooltips.add(button3, {text: "Delete", direction: 'bottom'});

			button4 = new IconButton(open, 'meumbutton4');
			button4.x = button3.x + button3.width + 20;
			button4.y = 10;
			button4.width = 50;
			button4.height = 50;		
			addChild(button4);
			SimpleTooltips.add(button4, {text: "Open", direction: 'bottom'});

			button5 = new IconButton(save, 'meumbutton5');
			button5.x = button4.x + button4.width + 20;
			button5.y = 10;
			button5.width = 50;
			button5.height = 50;		
			addChild(button5);
			SimpleTooltips.add(button5, {text: "Save", direction: 'bottom'});

			button6 = new IconButton(debug, 'meumbutton6');
			button6.x = button5.x + button5.width + 20;
			button6.y = 10;
			button6.width = 50;
			button6.height = 50;		
			addChild(button6);
			SimpleTooltips.add(button6, {text: "Check", direction: 'bottom'});

			button7 = new IconButton(language, 'meumbutton7');
			button7.x = button6.x + button6.width + 20;
			button7.y = 10;
			button7.width = 50;
			button7.height = 50;		
			addChild(button7);
			SimpleTooltips.add(button7, {text: "EN/JP", direction: 'bottom'});

			button8 = new IconButton(close, 'meumbutton8');
			button8.x = button7.x + button7.width + 20;
			button8.y = 10;
			button8.width = 50;
			button8.height = 50;
			addChild(button8);
			SimpleTooltips.add(button8, {text: "Exit", direction: 'bottom'});

			icon_b1 = new IconButton(windows_min, 'icon_min');
			icon_b1.x = app.stage.stageWidth-99;
			icon_b1.y = 0;
			icon_b1.width = 32;
			icon_b1.height = 32;
			app.stage.addChild(icon_b1);
			
			icon_b2 = new IconButton(windows_max, 'icon_max');
			icon_b2.x = app.stage.stageWidth-66;
			icon_b2.y = 0;
			icon_b2.width = 32;
			icon_b2.height = 32;
			app.stage.addChild(icon_b2);
			
			icon_b3 = new IconButton(windows_normal, 'icon_normal');
			icon_b3.x = app.stage.stageWidth-66;
			icon_b3.y = 0;
			icon_b3.width = 32;
			icon_b3.height = 32;
			app.stage.addChild(icon_b3);
			icon_b3.visible = false;

			icon_b4 = new IconButton(close, 'icon_close');
			icon_b4.x = app.stage.stageWidth-33;
			icon_b4.y = 0;
			icon_b4.width = 32;
			icon_b4.height = 32;
			app.stage.addChild(icon_b4);

		    indicator = new IndicatorLight();
			indicator.addEventListener(MouseEvent.CLICK, function(e:Event):void {IQCar.app.showTip('extensions');}, false, 0, true);

			indicator.x = 200;/*179+60;*///app.palette.width - 30;
			indicator.y = 145;
			app.stage.addChild(indicator);

			this.x = 0;
			this.y = 0;
			this.width = button8.x +50;
			this.height = 50;
			app.stage.addChild(this);

			SetDeviceStatus(DEVICES_MODE_NO_DEVICE);
			setTimeout(CheckDeviceStatus, 2000);
		}
		
		public function getDeviceStatus():int
		{
		  return DeviceMode;
		}

		public function getComport():String
		{
		  return SerialPortNumber;
		}
		public var fWntState_Max:Boolean = false;
		public function windows_icon_set():void{
			
			 var x:int = 0;
			if (fWntState_Max)
			{
				x = app.stage.fullScreenWidth;
				icon_b3.x = x-66;
				icon_b2.visible = false;
				icon_b3.visible = true;
			}
			else
			{
				x = app.stage.stageWidth;
				icon_b2.x = app.stage.stageWidth-66;
				icon_b2.visible = true;
				icon_b3.visible = false;
			}

			icon_b1.x = x-99;
			icon_b4.x = x-33;
		}
		private function windows_min(b:IconButton):void{
			trace("windows_min");
			b.turnOff();
			app.stage.nativeWindow.minimize();
			//fWntState_Max = false;
			//windows_icon_set(fWntState_Max);
		}
		
		private function windows_max(b:IconButton):void{
			trace("windows_max");
			b.turnOff();
			app.stage.nativeWindow.maximize();
			//app.SetWindwosMax();
			fWntState_Max = true;
			//windows_icon_set(fWntState_Max);
			
			
		}
		
		private function windows_normal(b:IconButton):void{
			trace("windows_normal")
		    b.turnOff();
			app.SetWindowXY();
			fWntState_Max = false;
			windows_icon_set();
		}
		public function StopDrag():void//停止移动窗口，回到初始位置
		{
			if (panel && panel.visible)
			{
				panel.stopDrag();
				panel.x = panel.s_x;
				panel.y = panel.s_y;
			}
		}

		private var notepad_process:NativeProcess = null;
		private function openpasstxt():void{
			if (notepad_process && notepad_process.running)
			{
		      notepad_process.exit(true);
			  notepad_process = null;
			}

			var nativeProcessStartupInfo:NativeProcessStartupInfo =new NativeProcessStartupInfo();

			var userDir:String = File.userDirectory.nativePath;
			var notepad:String = userDir.substr(0,1) + ":/Windows/system32/notepad.exe";

			var file:File = new File(notepad);
			nativeProcessStartupInfo.executable = file;

			var processArgs:Vector.<String> = new Vector.<String>();
			processArgs.push(File.userDirectory.resolvePath("AppData/Roaming/Avalon/pass.txt").nativePath);
			//processArgs.push("C:/Users/liuzg/AppData/Avalon/pass.txt");
			nativeProcessStartupInfo.arguments = processArgs;

			notepad_process = new NativeProcess();
			notepad_process.start(nativeProcessStartupInfo);
		}
		public function writefile(str:String):void{
			var file:File = new File(File.userDirectory.resolvePath("AppData/Roaming/Avalon/pass.txt").nativePath);
			trace(file.nativePath);
			trace("len="+str.length);
			trace(str);
			FileUtil.WriteString(file, str);
		}

		private function letsmove(b:IconButton):void{
			
		    b.turnOff();
			if (IQCar.cls && IQCar.cls.letsmove)
			{
				IQCar.cls.letsmove(app.scriptsPane.numChildren,
					               app.scriptsPane.getChildForIndex, 
					               app.scriptsPane.IsBlockObj,
					               app.scriptsPane.IsBlockArgObj, 
								   app.scriptsPane.MakeBlockObj, 
								   app.scriptsPane.IsVar);
			}
			/*
			var str:String = "";
		    str = app.scriptsPane.get_script_code();
			if (str == null)
			{
			  trace("脚本为空");
			  return;
			}
			writefile(str);*/
			//openpasstxt();
		}

		private var process:NativeProcess;
		private var errorText:String;
		private var output:String;
		private function onOutputData(event:ProgressEvent):void
		{
			output = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
			var date:Date = new Date;
			//IQCar.app.scriptsPart.appendMessage(""+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes+": Got: "+output);
		}

		private function onErrorData(event:ProgressEvent):void
		{
			var errOut:String = process.standardError.readUTFBytes(process.standardError.bytesAvailable);

			if(null == errorText){
				errorText = errOut;
			}else{
				errorText += errOut;
			}
		}

		private function SetDeviceStatus(status:int):void
		{
			DeviceMode = status;

			if ((CheckStatus > CHECK_STATUS_NULL) && (CheckStatus < CHECK_STATUS_DEBUG))
			{
				indicator.updateIndicatorEx(DEVICES_MODE_ENTER_DEBUG);
			}
			else
			{
			    indicator.updateIndicatorEx(status);
			}
		}

		private function onExit(event:NativeProcessExitEvent):void
		{
			var date:Date = new Date;
			//IQCar.app.scriptsPart.appendMessage(""+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes+": Process exited with "+event.exitCode);

			if(event.exitCode > 0 || (WaitCheckCount > 0)){
				trace("Device fail\n");
				//IQCar.app.scriptsPart.appendMsgWithTimestamp(errorText, true);
				errorText = null;

				/*
				//解析输出内容,找到工作模式的
				getComPortNumber();
				if (SerialPortNumber == "")
				{
					SetDeviceStatus(DEVICES_MODE_NO_DEVICE);

					if (CheckStatus == CHECK_STATUS_UPLOAD_END && (getTimer() - enterdebug_tick > 1000*8))
					{//timeout
						CheckStatus = CHECK_STATUS_END;
						app.showDialogBox('Mini-Q check', 'Entering Mini-Q check fail');
					}
				}
				else
				{
					if (CheckStatus == CHECK_STATUS_UPLOAD_END)
					{
						SetDeviceStatus(DEVICES_MODE_DEBUG);
						CheckStatus = CHECK_STATUS_LOAD_DEBUG;
						load_debug();
					}
					else
					{
						if (DeviceMode != DEVICES_MODE_DEBUG)
						{
						  SetDeviceStatus(DEVICES_MODE_WORK);
						}

					}
				}
				*/
				WaitCheckCount = 0;

				SetDeviceStatus(DEVICES_MODE_NO_DEVICE);
			}
			else
			{
			  //trace("Device success\n");
			  SetMode();
			  /*
			  app.log("===========STATUS:DEVICES_MODE_BOOTLOADER");
			  SetDeviceStatus(DEVICES_MODE_BOOTLOADER);*/
			}

			ischecking = false;
		}

		private function SetMode():void
		{
			if (output == null) return;

			var list:Array = output.split('\r\n');
			var line:Array;
			SerialPortNumber = "";

			//app.log("SetMode:"+output);

			if (list[0].indexOf("bootloader mode") > -1)
			{
			    SetDeviceStatus(DEVICES_MODE_BOOTLOADER);

				SerialPortNumber = "COM"+list[1];
			}
			else if (list[0].indexOf("work mode") > -1)
			{
				SerialPortNumber = "COM"+list[1];
				if (CheckStatus == CHECK_STATUS_UPLOAD_END)
				{
					SetDeviceStatus(DEVICES_MODE_DEBUG);
					
					CheckStatus = CHECK_STATUS_LOAD_DEBUG;
					enterdebug_tick = getTimer();
					load_debug();
				}
				else
				{
					if (DeviceMode != DEVICES_MODE_DEBUG)
					{
						SetDeviceStatus(DEVICES_MODE_WORK);
					}

				}
			}
			else
			{
			    SetDeviceStatus(DEVICES_MODE_NO_DEVICE);

				if (CheckStatus == CHECK_STATUS_UPLOAD_END && (getTimer() - enterdebug_tick > 1000*12))
				{//timeout
					app.log("-------------:"+getTimer()+","+enterdebug_tick);
					CheckStatus = CHECK_STATUS_END;
					app.showDialogBox('Mini-Q check', 'Entering Mini-Q check fail');
				}
			}
		}


		private function getComPortNumber():void
		{
			if (output == null) return;

		  var list:Array = output.split('\r\n');
		  var line:Array;
          SerialPortNumber = "";
		  for(var i:int=0; i<list.length; i++)
		  {
			  if (list[i].indexOf("Trying to connect on") == -1 || list[i+1].indexOf("Set binary mode") == -1)
			  {
			    continue;
			  }

			  line = list[i].split(' ');

			  if (line[4].indexOf("COM") == -1)
			  {
			    continue;
			  }

			  app.log('getComPortNumber:'+line[4]);
			  SerialPortNumber = line[4];
			  break;
		  }
		}

		private function checkupdatestate():void
		{
			if (ArduinoManager.sharedManager().isUploading == false)
			{
				cancleMaskLayers();
				return;
			}

			setTimeout(checkupdatestate, 1000);
		}

		private function checkusbserial():void{
			var nativeProcessStartupInfo:NativeProcessStartupInfo =new NativeProcessStartupInfo();
			/*
			var file:File = new File(ArduinoManager.sharedManager().arduinoInstallPath+"/hardware/tools/bossac/1.7.0/bossac"+(ApplicationManager.sharedManager().system==ApplicationManager.WINDOWS?".exe":""));
			var processArgs:Vector.<String> = new Vector.<String>();
			var cmd:Array = ["-d"];
			nativeProcessStartupInfo.executable = file;
			processArgs.push(cmd[0]);
			nativeProcessStartupInfo.arguments = processArgs;
			*/

			var file:File = new File(ArduinoManager.sharedManager().arduinoInstallPath+"/hardware/tools/serial/serial"+(ApplicationManager.sharedManager().system==ApplicationManager.WINDOWS?".exe":""));
			nativeProcessStartupInfo.executable = file;

			process = new NativeProcess();
			process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
			process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
			process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
			process.start(nativeProcessStartupInfo);
		}

		private var WaitCheckCount:int = 0;
		private var ischecking:Boolean = false;

		private function CheckDeviceStatus():void
		{
			/*if (Resources.count == 1)
			{
				if (icon_b1)
					app.stage.removeChild(icon_b1);
				icon_b1 = new IconButton(windows_min, 'icon_min');
				icon_b1.x = app.stage.stageWidth-99;
				icon_b1.y = 0;
				icon_b1.width = 32;
				icon_b1.height = 32;
				app.stage.addChild(icon_b1);
			}*/
			
			
		  if (ischecking == true)
		  {
			if (WaitCheckCount > 6)//防止串口检测程序卡死
			{
				if (process && process.running)
				{
				  process.exit(true);
				  app.closeDialogBox();
				}
			}
			else
			{
			  WaitCheckCount++;
		      app.log("ischecking == true");
			}
		  }
		  else if (DownLoadStatus == DOWNLOAD_STATUS_READY)
		  {
			  DownLoadStatus = DOWNLOAD_STATUS_UPLOAD;
			  app.log("DownLoadStatus == DOWNLOAD_STATUS_READY");
			  app.scriptsPart.onCompileArduino();
		  }
		  else if (DownLoadStatus == DOWNLOAD_STATUS_UPLOAD)
		  {
		    if (ArduinoManager.sharedManager().isUploading == false)
			{
				DownLoadStatus = DOWNLOAD_STATUS_NULL;
				cancleMaskLayers();//取消遮罩层
			}
		  }
		  else if (CheckStatus == CHECK_STATUS_READY_UPLOAD)
		  {
			app.log("CheckStatus == CHECK_STATUS_READY_UPLOAD");
		    ischecking = true;
			WaitCheckCount = 0;
			uploadDebugBin();
		  }
		  else if (CheckStatus == CHECK_STATUS_UPLOADING)
		  {
			  app.log("CheckStatus == CHECK_STATUS_UPLOADING");
		  }
		 /* else if (CheckStatus == CHECK_STATUS_UPLOAD_END)
		  {
			  app.log("CheckStatus == CHECK_STATUS_UPLOAD_END");
			  if ((getTimer() - enterdebug_tick) > 6*1000)
			  {
				  app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
				  debug_end();
				  DeviceMode = DEVICES_MODE_NO_DEVICE;
  
			  }
			  
			  if (ArduinoManager.sharedManager().isUploading == false && ischecking == false)
			  {
				  //app.log("checkusbserial:"+CheckStatus);
				  ischecking = true;
				  checkusbserial();
			  }
			  
		  }*/
		  else if (CheckStatus == CHECK_STATUS_END)
		  {
			  debug_end();
			  app.log("CheckStatus == CHECK_STATUS_END");
			  if (ArduinoManager.sharedManager().isUploading == false && ischecking == false)
			  {
				  //app.log("checkusbserial:"+CheckStatus);
				  ischecking = true;
				  checkusbserial();
			  }
		  }
		  else if (CheckStatus >= CHECK_STATUS_LOAD_DEBUG)
		  {
			  if (CheckStatus >= CHECK_STATUS_ENTER_DEBUG)
			  {
			      if ((getTimer() - startTime) > 3*1000)//操作超时
				  {
				    switch(CheckStatus)
					{
						case CHECK_STATUS_ENTER_DEBUG:
						{
							//enter debug modee fail.
							app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
							debug_end();
							DeviceMode = DEVICES_MODE_NO_DEVICE;
						}
							break;
						case CHECK_STATUS_EXIT_DEBUG:
						{
							//exit debug mode fail.
							debug_end();
						}
							break;
						case CHECK_STATUS_OPEN_AUDIO_MAX_VALUE_SWITCH:
						{
						    app.closeDialogBox();
						}
							break;
						case CHECK_STATUS_CLOSE_AUDIO_MAX_VALUE_SWITCH:
						{
						    app.closeDialogBox();
						}
							break;
						default:
							app.log("CheckDeviceStatus:unknown status!!!");
							break;
					}
				  }
			  }
			  else if (CheckStatus == CHECK_STATUS_LOAD_DEBUG)
			  {
				  if ((getTimer() - enterdebug_tick) > 6*1000)
				  {
					  app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
					  debug_end();
					  DeviceMode = DEVICES_MODE_NO_DEVICE;

					  if (ArduinoManager.sharedManager().isUploading == false && ischecking == false)
					  {
						  //app.log("checkusbserial:"+CheckStatus);
						  ischecking = true;
						  checkusbserial();
					  }
				  }
			  }
			  else
			  {
			      SetDeviceStatus(DEVICES_MODE_DEBUG);
			  }
			  //app.log("CheckStatus == CHECK_STATUS_LOAD_DEBUG");
		  }
		  else if (ArduinoManager.sharedManager().isUploading == false && ischecking == false)
		  {
			//app.log("checkusbserial:"+CheckStatus);
		    ischecking = true;
		    checkusbserial();
		  }

		 // if ((CheckStatus > CHECK_STATUS_NULL) && (CheckStatus < CHECK_STATUS_NULL))
		  //{
		//	  SetDeviceStatus(DEVICES_MODE_ENTER_DEBUG);
		  //}

		  setTimeout(CheckDeviceStatus, 2000);
		}

		private function debug_end():void{
			SerialAgent.sharedManager().close();
			//SerialManager.sharedManager().close();
			
			if (panel)
			{
				if (panel.audio_switch_remove_event)
				{
					panel.audio_switch_remove_event();
				}
				
				app.stage.removeChild(panel);
				// panel.visible(false);
				panel.closeReleased();
				panel = null;
			}
			
			cancleMaskLayers();
			CheckStatus = CHECK_STATUS_NULL;
		}

		//private var fdownload:Boolean = false;
		private var DownLoadStatus:int = 0;
		private var DOWNLOAD_STATUS_NULL:int = 0;
		private var DOWNLOAD_STATUS_READY:int = 1;
		private var DOWNLOAD_STATUS_UPLOAD:int = 2;
		//private var DOWNLOAD_STATUS_UPLOAD_END:int = 3;
		private function download(b:IconButton):void
		{
			b.turnOff();

			if (app.scriptsPane.IsScriptPaneNotNull() == false)
			{
			  return;
			}

			if (ArduinoManager.sharedManager().isUploading == true)
			{
			  return;
			}

			if (DownLoadStatus != DOWNLOAD_STATUS_NULL)
			{
              return;
			}

			app.scriptsPart.Get_C_Code();

			app.showDialogBox('download', 'USB download check', false);
			//check usb serial
			//checkusbserial();

			if (DeviceMode != DEVICES_MODE_BOOTLOADER)
			{
				app.showDialogBox('download', 'Please check USB cable and Power SW of Mini-Q');
				return;
			}
			//onCompileArduino

			//fdownload = true;
			DownLoadStatus = DOWNLOAD_STATUS_READY;
			setMaskLayers();
			//app.scriptsPart.onCompileArduino();
		}

		private function deletepj(b:IconButton):void{
			b.turnOff();
			if (IQCar.cls && IQCar.cls.deleteprj)
			{
				IQCar.cls.deleteprj(app.scriptsPane.IsScriptPaneNotNull(), app.clearProject, Translator.map, app.stage);
			}
		  //app.deleteproject();

		}

		private function open(b:IconButton):void{
			b.turnOff();
			if (IQCar.cls && IQCar.cls.open)
			{
				IQCar.cls.open(app.scriptsPane.IsScriptPaneNotNull(), Translator.map, app.runtime.stopAll, app.runtime.installProjectFromFile , app.stage);
			}

	        //app.runtime.selectProjectFile();
		}

		private function save(b:IconButton):void{
			b.turnOff();
			if (IQCar.cls && IQCar.cls.save)
			{
				IQCar.cls.save(app.scriptsPane.IsScriptPaneNotNull(), PopupUtil.showQuitAlert, app.exportProjectToFile);
			}
			//app.saveProjectAndThen();
		}

		//mask layers
		private function setMaskLayers():void
		{
			if (label_test != null)
			{
			  return;
			}

			label_test = new JLabel(null, null);
			label_test.setBounds(new IntRectangle(0, 0, app.stage.stageWidth, 60));
			label_test.alpha = 0;
			app.stage.addChild(label_test);
		}

		private function cancleMaskLayers():void
		{
			if (label_test == null)
			{
			  return;
			}

			app.stage.removeChild(label_test);
			label_test = null;
			//panel = null;
		}
		private function debug_close():void
		{
			if (panel == null || panel.visible == false)
			{
     		  trace("debug_close");

			  //exit debug mode
			  if (panel)
			  {
				panel.audio_switch_remove_event();
			  }
			  exit_Debug_mode();
			  //cancleMaskLayers();//test

			 // if (CheckStatus != CHECK_STATUS_NULL || CheckStatus != CHECK_STATUS_END)
			 // {
			//	trace("end2++++++++++++++++++++++");
			  //  CheckStatus = CHECK_STATUS_END;
			  //}
			}
			else
			{
			  setTimeout(debug_close, 1000);
			}
		}

		//private var iDelayCount:int = 0;
		///private var DebugStatus:int = 0;// 1 请求进入DEBUG模式     2请求退出debug模式， 3 启动音量检测    4  退出音量检测
		//private var fDebug:Boolean = false;
		private function GointoDebugMode():void
		{
		  if (DeviceMode != DEVICES_MODE_DEBUG || CheckStatus != CHECK_STATUS_SERIAL_CONNECTED )
		  {
			  CheckStatus = CHECK_STATUS_END;
			  app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
  		      return;
		  }

  		  var data:Array = [0xff, 0xfe, 0x01, 0x02, 0x0d, 0x0a];
		  //SerialManager.sharedManager().sendByte_array(data);
		  SerialAgent.sharedManager().sendBytes(data);

		  IQCar.app.log("GointoDebugMode  end");

		  CheckStatus = CHECK_STATUS_ENTER_DEBUG;
		  startTime = getTimer();
		}

		private var startTime:Number = 0;
		//private var fAudioSwitch:Boolean = false;
		public function audio_switch_function(evt:AWEvent):void
		{
			if ((CheckStatus != CHECK_STATUS_DEBUG) && (CheckStatus != CHECK_STATUS_KEEP_AUDIO_MAX_VALUE))
			{
			  return;
			}

			var data:Array = [0xff, 0xfe, 0x01, 0x04, 0x0d, 0x0a];

			if (CheckStatus == CHECK_STATUS_DEBUG)
			{
				//SerialManager.sharedManager().sendByte_array(data);
				SerialAgent.sharedManager().sendBytes(data);
				CheckStatus = CHECK_STATUS_OPEN_AUDIO_MAX_VALUE_SWITCH;
				app.showDialogBox('Mini-Q check', 'Opening the keep sound max value configure', false);
				startTime = getTimer();
			}
			else if (CheckStatus == CHECK_STATUS_KEEP_AUDIO_MAX_VALUE)
			{
				//var data:Array = [0xff, 0xfe, 0x01, 0x05, 0x0d, 0x0a];
				data[3] = 0x05;

				//SerialManager.sharedManager().sendByte_array(data);
				SerialAgent.sharedManager().sendBytes(data);
				CheckStatus = CHECK_STATUS_CLOSE_AUDIO_MAX_VALUE_SWITCH;
				app.showDialogBox('Mini-Q check', 'Cancel the keep sound max value configure', false);
				startTime = getTimer();
			}
			else
			{
			    app.log("audio_switch_function: unknown error");
			}
		}
		private function exit_Debug_mode():void
		{
			if (CheckStatus < CHECK_STATUS_DEBUG)
			{
			  return;
			}
			
		    var data:Array = [0xff, 0xfe, 0x01, 0x03, 0x0d, 0x0a];

			//SerialManager.sharedManager().sendByte_array(data);
			SerialAgent.sharedManager().sendBytes(data);
			CheckStatus = CHECK_STATUS_EXIT_DEBUG;
			startTime = getTimer();
		}

		private function recv_serial_data():void
		{
			if ((CheckStatus >= CHECK_STATUS_ENTER_DEBUG) && ((getTimer() - startTime) > 3*1000))
			{
			  switch(CheckStatus)
			  {
			  case CHECK_STATUS_ENTER_DEBUG:
			  {
				  //enter debug modee fail.
				  app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
			  }
				  break;
			  case CHECK_STATUS_EXIT_DEBUG:
			  {
				  //exit debug mode fail.
			  }

				  //if (fDebug)
				  //{
					  //app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
				  //}
				  break;
			  case CHECK_STATUS_OPEN_AUDIO_MAX_VALUE_SWITCH://open audio data collection switch fail
			  {
				  app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
			  }
				  break;
			  case CHECK_STATUS_CLOSE_AUDIO_MAX_VALUE_SWITCH://close audio data collection switch fail
			  {
				  app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
			  }
				  break;
			  default:
				  return;
			  }

			  app.log("recv_serial_data: timeout.");
			  if (CheckStatus != CHECK_STATUS_END || CheckStatus != CHECK_STATUS_NULL)
			  {
				  CheckStatus = CHECK_STATUS_END;
			  }

			  return;
			}
/*
			var arr:Array = HexUtil.bytesToArray(SerialManager.sharedManager().readBytes());//read serial data

			if (arr.length > 5)
			{
				IQCar.app.log("recv_serial_data");
				parseMessage(arr);
			}
*/
			setTimeout(recv_serial_data, 100);
		}

		public function parseMessage(recv_data:Array):void
		{
			var b_len:int  = 0;

			IQCar.app.log("parseMessage:"+recv_data.join(" "));

			while(recv_data.length)
			{
				if(recv_data[0] != 0xff)
				{
					IQCar.app.log("parseMessage err1 "+ recv_data[0]);
					recv_data.splice(0, 1);
					continue;
				}

				if(recv_data[1] != 0xfe)
				{
					IQCar.app.log("parseMessage err2 "+ recv_data[1]);
					recv_data.splice(0, 2);
					continue;
				}

				b_len = recv_data[2];
				if (b_len == 0 || recv_data[2+b_len+1] != 0x0d || recv_data[2+b_len+2] != 0x0a)
				{
					IQCar.app.log("parseMessage err3 "+ recv_data[2+b_len+1]);
					IQCar.app.log("parseMessage err4 "+ recv_data[2+b_len+2]);
					IQCar.app.log("parseMessage err5 "+ b_len);
					recv_data.splice(0, 3);
					continue;
				}

				var type:int = recv_data[3];
				switch(type)
				{
					case 0x10:
					{
						if (b_len != 3)
						{
						  IQCar.app.log("parseMessage err6 "+ b_len);
						  break;
						}

						switch(CheckStatus)
						{
						case CHECK_STATUS_ENTER_DEBUG:
						{
							if (recv_data[4] != 0x02)
							{
							  break;
							}

							CheckStatus = CHECK_STATUS_DEBUG;
							IQCar.app.log("parseMessage showdebug");
							IQCar.app.showDialogBox('Mini-Q check', 'Loading Mini-Q check', true, true, 1);
							showdebug();
						}
							break;
						case CHECK_STATUS_EXIT_DEBUG:
						{
							//if (CheckStatus != CHECK_STATUS_END || CheckStatus != CHECK_STATUS_NULL)
							//{
								CheckStatus = CHECK_STATUS_END;
							//}

							//SerialManager.sharedManager().close();
							SerialAgent.sharedManager().close();
							IQCar.app.log("parseMessage exit debug");
						}
							break;
						case CHECK_STATUS_OPEN_AUDIO_MAX_VALUE_SWITCH:
						{
							CheckStatus = CHECK_STATUS_KEEP_AUDIO_MAX_VALUE;

							if (panel)
							{
								panel.audio_switch_icon_translator(true);
								app.closeDialogBox();
								//app.showDialogBox('Mini-Q check', 'Opening the configure success', true, true, 100);
							}
						}
							break;
						case CHECK_STATUS_CLOSE_AUDIO_MAX_VALUE_SWITCH:
						{
							CheckStatus = CHECK_STATUS_DEBUG;

							if (panel)
							{
								panel.audio_switch_icon_translator(false);
								app.closeDialogBox();
								//app.showDialogBox('Mini-Q check', 'Cancaling the configure success', true, true, 100);
							}
						}
							break;
						default:
							break;
						}
					}
						break;
					case 0x14://保留
						break;
					case 0x15:
					case 0x16:
					{
						if (!panel) return;
						if (b_len == 3 && CheckStatus >= CHECK_STATUS_DEBUG)
						{
							//IQCar.app.log("parseMessage sensor_active");
							panel.sensor_active(recv_data[3], recv_data[4], recv_data[5]);
						}
						else
						{
							return;
						}
					}
						break;
					case 0x17:
					{
						if (!panel) break;

						if (b_len == 5 && CheckStatus >= CHECK_STATUS_DEBUG)
						{
							//IQCar.app.log("parseMessage ls_active");
							if (panel)
							{
							   panel.ls_active((recv_data[4] << 8)+recv_data[5], (recv_data[6] << 8)+recv_data[7]);
							}
						}
						else
						{
						  return;
						}
					}
						break;
					case 0x18:
					{
						if (!panel)
						{
						  return;
						}
					    if (b_len == 3 )
						{
							if (CheckStatus == CHECK_STATUS_DEBUG)
							{
								panel.audio_active(false, (recv_data[4] << 8)+recv_data[5]);
							}
							else if (CheckStatus == CHECK_STATUS_KEEP_AUDIO_MAX_VALUE)
							{
								panel.audio_active(true, (recv_data[4] << 8)+recv_data[5]);
							}
						}
						else
						{
						  return;
						}
					}
						break;
					default:
						break;
				}

				recv_data.splice(0, 5+b_len);
			}
		}
		
		//private var recv_bytes:ByteArray;
		private function showdebug():void
		{
			if (panel == null)
			{
				//app.runtime.stopAll();
				panel = new DeviceDebug(app);
				//panel.addEventListener(Event.CLOSE, debug_close, false, 32);

				setTimeout(debug_close, 1000);

				trace("debug test\n");
				app.stage.addChild(panel);
			}
			panel.show();
		}
		
		private function onUploadBinErrorData(event:ProgressEvent):void
		{
			var errOut:String = process.standardError.readUTFBytes(process.standardError.bytesAvailable);
			
			if(null == errorText){
				errorText = errOut;
			}else{
				errorText += errOut;
			}
		}
		
		private var enterdebug_tick:Number = 0;
		private function onUploadHexExit(event:NativeProcessExitEvent):void
		{
			var date:Date = new Date;
			IQCar.app.scriptsPart.appendMessage(""+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes+": Process exited with "+event.exitCode);

			if(event.exitCode > 0 && errorText.indexOf("SAM-BA operation failed") <= 0){
				trace("Device fail\n");
				IQCar.app.scriptsPart.appendMsgWithTimestamp(errorText, true);
				errorText = null;
				//fEnteringDebug = false;
				CheckStatus = CHECK_STATUS_END;
				//app.showDialogBox('Mini-Q check', 'Downloading Mini-Q check application fail');
				app.showDialogBox('Mini-Q check', 'Cannot enter debug mode');
			}
			else
			{
				//d.cancel();
				//trace("Device success\n");
				//app.showDialogBox('Mini-Q check', 'Downloading Mini-Q check application success', false);

				enterdebug_tick = getTimer();
				//fDebugCheck = true;
				CheckStatus = CHECK_STATUS_UPLOAD_END;
				app.log("==============:"+enterdebug_tick);
				app.showDialogBox('Mini-Q check', 'Checking Device status', false);
			}
			
			ischecking = false;
		}

		//private var fUploading:Boolean = false;
		private function uploadDebugBin():void{
				var nativeProcessStartupInfo:NativeProcessStartupInfo =new NativeProcessStartupInfo();
				var file:File = new File(ArduinoManager.sharedManager().arduinoInstallPath+"/hardware/tools/bossac/1.7.0/bossac"+(ApplicationManager.sharedManager().system==ApplicationManager.WINDOWS?".exe":""));
				var processArgs:Vector.<String> = new Vector.<String>();
				var workdir:File = new File( ArduinoManager.sharedManager().arduinoInstallPath+"\\build\\debug");
				var cmd:Array = ["-e", "-w", "-v", "-b" , "-R"];
				nativeProcessStartupInfo.executable = file;
				nativeProcessStartupInfo.workingDirectory = workdir;
				processArgs.push(cmd[0]);
				processArgs.push(cmd[1]);
				processArgs.push(cmd[2]);
				processArgs.push(cmd[3]);
				processArgs.push(cmd[4]);
				processArgs.push("debug.ino.bin");
				nativeProcessStartupInfo.arguments = processArgs;
				IQCar.app.scriptsPart.appendMessage(nativeProcessStartupInfo.executable.nativePath+" " + nativeProcessStartupInfo.arguments.join(" "));
				process = new NativeProcess();
				//process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onUploadHexOutputData);
				process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onUploadBinErrorData);
				process.addEventListener(NativeProcessExitEvent.EXIT, onUploadHexExit);

				process.start(nativeProcessStartupInfo);

				CheckStatus = CHECK_STATUS_UPLOADING;
		}

		private function debug(b:IconButton):void{//动起来
			//button1.disableMouseover();
			b.turnOff();

			if (CheckStatus != CHECK_STATUS_NULL)//不允许重复操作
			{
			  return;
			}

			app.showDialogBox('Mini-Q check', 'USB download check', false);
			/*
			setMaskLayers();
			DeviceMode = DEVICES_MODE_DEBUG;
			SerialPortNumber = "COM16";
			CheckStatus = CHECK_STATUS_UPLOAD_END;
			return;
			*/
			//检查设备模式
			if (DeviceMode == DEVICES_MODE_DEBUG && (SerialPortNumber != ""))
			{
  			  setMaskLayers();
			  enterdebug_tick = getTimer();
			  CheckStatus = CHECK_STATUS_UPLOAD_END;
			  return;
			}
			else if (DeviceMode != DEVICES_MODE_BOOTLOADER)
			{
				app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
				return;
			}

			app.showDialogBox('Mini-Q check', 'Downloading', false);
			//上传debug app

			CheckStatus = CHECK_STATUS_READY_UPLOAD;
			SetDeviceStatus(DEVICES_MODE_ENTER_DEBUG);
			setMaskLayers();
			/*
			DeviceMode = DEVICES_MODE_DEBUG;
			CheckStatus = CHECK_STATUS_LOAD_DEBUG;
			SerialPortNumber = "COM16";
			load_debug();*/
		}

		private function load_debug():void
		{
			if ((DeviceMode != DEVICES_MODE_DEBUG) || (CheckStatus != CHECK_STATUS_LOAD_DEBUG) || (SerialPortNumber == ""))
			{
				IQCar.app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
			    return;
			}
	
			IQCar.app.showDialogBox('Mini-Q check', 'Loading Mini-Q check', false);
			app.log("load_debug");


			SerialAgent.sharedManager().open(SerialPortNumber, parseMessage, get_sa_status);
			/*if (SerialManager.sharedManager()._open(SerialPortNumber, parseMessage, get_sa_status) == true)
			{
				app.log("load_debug: open success");
				get_sa_status(true);
			}*/
		}

		public function get_sa_status(status:Boolean):void
		{
			if (status)
			{
				//串口连接
				if (CheckStatus == CHECK_STATUS_LOAD_DEBUG)
				{
					CheckStatus = CHECK_STATUS_SERIAL_CONNECTED;
				    GointoDebugMode();
				}
				return;
			}
			else
			{
			  //IQCar.app.showDialogBox('Mini-Q check', 'Please check USB cable and Power SW of Mini-Q');
				if (CheckStatus > CHECK_STATUS_NULL && CheckStatus < CHECK_STATUS_END)
				{
				  CheckStatus = CHECK_STATUS_END;
				}
			}
		}
		private function language(b:IconButton):void{
			b.turnOff();
			if (IQCar.cls && IQCar.cls.language)
			{
  			  IQCar.cls.language(Translator.updateWindowsAction);
			}
			
			/*
			if (Translator.currentLang == 'en')
			{
				Translator.setLanguage('ja');
			}
			else //if (Translator.currentLang == 'ja')
			{
			  Translator.setLanguage('en');
			}*/
		}

		private function close(b:IconButton):void{
			b.turnOff();
			if (IQCar.cls && IQCar.cls.close)
			{
			  IQCar.cls.close(app.scriptsPane.IsScriptPaneNotNull(), PopupUtil.showQuitAlert, app.exportProjectToFile, app.quitApp);
			}
			//app.saveProjectAndThen(app.quitApp);
			
		}

	}
}