
function AutomatedtestsAssistant() {
	this.commandMenuItems = new Array();
	this.commandMenuModel = {
			visible:true,
			items: [{ }] 
    };
	this.cmdmenuItemSkipDone = new Object();
}

AutomatedtestsAssistant.prototype.ipAddressRegExp = /^\s*(\d{1,3}\.){3}\d{1,3}\s*$/;
AutomatedtestsAssistant.prototype.macAddressRegExp = /^\s*([\d[a-f]{2}:){5}[\d[a-f]{2}\s*$/;
AutomatedtestsAssistant.prototype.macAddressRegExpUp = /^\s*([\d[A-F]{2}:){5}[\d[A-F]{2}\s*$/;

AutomatedtestsAssistant.prototype.memory = 'quicktestMemory';
AutomatedtestsAssistant.prototype.wifi = 'quicktestWifi';
AutomatedtestsAssistant.prototype.bluetooth = 'quicktestBluetooth';
AutomatedtestsAssistant.prototype.modem = 'quicktestModem';

AutomatedtestsAssistant.prototype.request = undefined;
AutomatedtestsAssistant.prototype.dimRequest = undefined;
AutomatedtestsAssistant.prototype.wanRequest = undefined;

AutomatedtestsAssistant.prototype.stopTests = false;
AutomatedtestsAssistant.prototype.isModemEnabled = true;
AutomatedtestsAssistant.prototype.isWifiEnabled = true;
AutomatedtestsAssistant.prototype.deviceHasWifi = true;

AutomatedtestsAssistant.prototype.sceneIntro = function()
{
	console.log("AutomatedtestsAssistant SceneIntro");
	this.controller.get('airplane').hide();
	this.controller.get('wifi').hide();
	this.controller.get('intro').show();	

	this.controller.get(this.memory).hide();
	this.controller.get(this.wifi).hide();
	this.controller.get(this.bluetooth).hide();
	this.controller.get(this.modem).hide();

	this.controller.get('airplaneOn').hide();
	this.controller.get('airplaneOff').hide();
	//this.controller.get('continue').hide();
	this.cmdmenuItemSkipDone.label = $L("Start");
    this.cmdmenuItemSkipDone.command = "handleButton";
   // this.commandMenuItems.push(this.cmdmenuItemSkipDone);
	
	//this.commandMenuModel.items = this.commandMenuItems;
	this.controller.modelChanged(this.commandMenuModel);
	//this.controller.get('button').show();
}

AutomatedtestsAssistant.prototype.sceneAirplane = function()
{
	this.controller.get('wifi').hide();
	this.controller.get('intro').hide();	
	this.controller.get('airplane').show();

	this.controller.get(this.memory).hide();
	this.controller.get(this.wifi).hide();
	this.controller.get(this.bluetooth).hide();
	this.controller.get(this.modem).hide();
	
	//this.controller.get('continue').hide();
	//this.controller.get('button').hide();
	this.controller.get('airplaneOn').show();
	this.controller.get('airplaneOff').show();
}

AutomatedtestsAssistant.prototype.sceneWifi = function()
{
	this.controller.get('intro').hide();	
	this.controller.get('airplane').hide();
	this.controller.get('wifi').show();

	this.controller.get(this.memory).hide();
	this.controller.get(this.wifi).hide();
	this.controller.get(this.bluetooth).hide();
	this.controller.get(this.modem).hide();

	//this.controller.get('button').hide();
	this.controller.get('airplaneOn').hide();
	this.controller.get('airplaneOff').hide();
	this.cmdmenuItemSkipDone.label = $L("Continue");
    this.cmdmenuItemSkipDone.command = "handleContinue";
    //this.commandMenuItems.push(this.cmdmenuItemSkipDone);
	
	//this.commandMenuModel.items = this.commandMenuItems;
	this.controller.modelChanged(this.commandMenuModel);
	//this.controller.get('continue').show();
}

AutomatedtestsAssistant.prototype.handleCommand = function(event) {
	if(event.type == Mojo.Event.command) {
		if (event.command == Mojo.Menu.helpCmd) {
			Event.stop(event);
			var openParams = {
				target: 'http://help.palm.com/device_info/index.html'
			};
			this.controller.serviceRequest('palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
					id: 'com.palm.app.help',
					params: openParams
				}
			});
		}else if (typeof this[event.command] == "function") {
			this[event.command](event);
		}
	} else if (event.type == Mojo.Event.commandEnable && 
		 (event.command == Mojo.Menu.helpCmd)) {
		event.stopPropagation();
	}
}

AutomatedtestsAssistant.prototype.setup = function() {
	this.appMenuModel = {
		visible: true,
		items: [Mojo.Menu.editItem, Mojo.Menu.helpItem]
	};
	this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel);
	
   console.log("AutomatedtestsAssistant Setup");
	var cmdmenuItem1 = new Object();
    this.commandMenuItems.push(cmdmenuItem1);
	var cmdmenuItem2 = new Object();
    this.commandMenuItems.push(cmdmenuItem2);
	this.cmdmenuItemSkipDone.label = $L("Start");
    this.cmdmenuItemSkipDone.command = "handleButton";
    this.commandMenuItems.push(this.cmdmenuItemSkipDone);
	
	this.commandMenuModel.items = this.commandMenuItems;

	
    this.controller.setupWidget(Mojo.Menu.commandMenu, {}, this.commandMenuModel);
	/*this.attributes = {
		disabledProperty: 'disabled',
		type: Mojo.Widget.defaultButton
	};

	this.model = {
		buttonLabel: $L("Start"),
		buttonClass: '',
		disabled: false
	};
	
	this.controller.setupWidget('button', this.attributes, this.model);
	this.controller.listen('button', Mojo.Event.tap, this.handleButton.bind(this));*/

	this.airplaneAttributes = {
		disabledProperty: 'disabled',
		type: Mojo.Widget.activityButton
	};

	this.airplaneModel = {
		buttonLabel: $L("Turn Airplane Mode Off"),
		buttonClass: '',
		disabled: false
	};

	this.controller.setupWidget('airplaneOff', this.airplaneAttributes, this.airplaneModel);
	this.controller.listen('airplaneOff', Mojo.Event.tap, this.handleAirplaneOff.bind(this));

	this.controller.setupWidget('memorySpinner', { spinnerSize: Mojo.Widget.spinnerSmall }, { spinning: true });
	this.controller.setupWidget('wifiSpinner', { spinnerSize: Mojo.Widget.spinnerSmall }, { spinning: true });
	this.controller.setupWidget('bluetoothSpinner', { spinnerSize: Mojo.Widget.spinnerSmall }, { spinning: true });
	this.controller.setupWidget('modemSpinner', { spinnerSize: Mojo.Widget.spinnerSmall }, { spinning: true });

	Mojo.Event.listen(this.controller.get('airplaneOn'),'mojo-tap', this.handleAirplaneOn.bind(this));
	//Mojo.Event.listen(this.controller.get('continue'),'mojo-tap', this.handleContinue.bind(this));
	var devInfo = Mojo.Environment.DeviceInfo;
	if (devInfo) {
		if (devInfo.wifiAvailable == true) {
			this.deviceHasWifi = true;
		}
		else {
			this.isWifiEnabled = false;
			this.deviceHasWifi = false;
		}
	}
	else
		this.deviceHasWifi = false;
  	/*var tmpRequest = new Mojo.Service.Request('palm://com.palm.crotest/GetFeatures', {
		parameters: {},
		onSuccess: function (features) {
			if(features.hasWifi)
				this.deviceHasWifi = true;
			else {
				this.isWifiEnabled = false;
				this.deviceHasWifi = false;
			}
		}.bind(this),
		onFailure: function() {
			console.log("Failed to retrieve phone features");
			this.deviceHasWifi = true;
		}.bind(this)
	});*/

	this.introScene = true;
	this.sceneIntro();
}

AutomatedtestsAssistant.prototype.activate = function() {
	this.request = new Array();
	QuickTestResults.initialize();

	if(this.stopTests)
		this.stopTests = false;

	this.disableDim();
}

AutomatedtestsAssistant.prototype.deactivate = function() {
	this.enableDim();

	if(this.wanRequest) {
		this.wanRequest.cancel();
		this.wanRequest = undefined;
	}

	if(!this.stopTests)
		this.stopTests = true;

	this.controller.get(this.memory).hide();
	this.controller.get(this.wifi).hide();
	this.controller.get(this.bluetooth).hide();
	this.controller.get(this.modem).hide();
	
	this.introScene = true;
	this.cmdmenuItemSkipDone.label = $L("Start");
    this.cmdmenuItemSkipDone.command = "handleButton";
   
	this.controller.modelChanged(this.commandMenuModel);
	//this.model.buttonLabel = $L("Start");
	//this.controller.modelChanged(this.model);
}

AutomatedtestsAssistant.prototype.startTest = function(test) {
	this.controller.get('airplane').hide();
	this.controller.get('wifi').hide();
	this.controller.get('intro').show();	

	this.controller.get(this.memory).hide();
	this.controller.get(this.wifi).hide();
	this.controller.get(this.bluetooth).hide();
	this.controller.get(this.modem).hide();

	this.controller.get('airplaneOn').hide();
	this.controller.get('airplaneOff').hide();
	//this.controller.get('continue').hide();
	//this.controller.get('button').show();                 

	this.controller.get(test).show();                                 

	if(!this.stopTests) {
		switch(test) {	
		case this.memory:	
			this.memoryTest();	
			break;
		case this.wifi:
			this.wifiTest();
			break;
		case this.bluetooth:
			this.bluetoothTest();
			break;
		case this.modem:
			this.modemTest();
			break;
		}                                                                
	}
}

AutomatedtestsAssistant.prototype.disableDim = function() {
        var parameters = {};
        parameters.requestBlock = true;
        parameters.client = Mojo.appName;
        parameters.subscribe = true;

	this.dimRequest = new Mojo.Service.Request('palm://com.palm.display/control', {
		method: 'setProperty',
		parameters: parameters
	});
}

AutomatedtestsAssistant.prototype.enableDim = function() {
        if (this.dimRequest){
            this.dimRequest.cancel();
            this.dimRequest = undefined;
        }
        
	var parameters = {};
        parameters.requestBlock = false;
        parameters.client = Mojo.appName;
        
	var tmpRequest = new Mojo.Service.Request('palm://com.palm.display/control', {
		method: 'setProperty',
		parameters: parameters

	});
}

AutomatedtestsAssistant.prototype.handleButton = function() {
	if(this.introScene)
	{
		this.checkAirplaneMode();

		this.introScene = false;
		this.cmdmenuItemSkipDone.label = $L("Stop");
    	this.cmdmenuItemSkipDone.command = "handleButton";
    	//this.commandMenuItems.push(this.cmdmenuItemSkipDone);
	
		//this.commandMenuModel.items = this.commandMenuItems;
		this.controller.modelChanged(this.commandMenuModel);
		//this.model.buttonLabel = $L("Stop");
		//this.controller.modelChanged(this.model);
	}
	else
	{
		this.stopTests = true;
		//pop back to deviceinfo more scene
		this.controller.stageController.popScenesTo("automatedtests");
	    this.controller.stageController.popScene();
		
	}
}

AutomatedtestsAssistant.prototype.handleAirplaneOn = function() {
	this.isWifiEnabled = false;
	this.isModemEnabled = false;
	this.startTest(this.memory);
}

AutomatedtestsAssistant.prototype.handleAirplaneOff = function() {
	var airplaneRequest = new Mojo.Service.Request("palm://com.palm.systemservice", { 
		method: 'setPreferences',
		parameters: {"airplaneMode":false},
		onComplete: function() {
			if(this.deviceHasWifi)
				setTimeout( this.checkWifi.bind(this), 5000 );
			else
				this.startTest(this.memory);
		}.bind(this),
	});
}

AutomatedtestsAssistant.prototype.handleContinue = function() {
	this.cmdmenuItemSkipDone.label = $L("Stop");
    this.cmdmenuItemSkipDone.command = "handleButton";
    this.controller.modelChanged(this.commandMenuModel);
	var wifiRequest = new Mojo.Service.Request('palm://com.palm.wifi', {
		method: 'getstatus',
		parameters: {"subscribe":false},
		onSuccess: function(response) {
			if(response.status == "serviceDisabled")
				this.isWifiEnabled = false;
			else
				this.isWifiEnabled = true;
		}.bind(this),
		onFailure: function() {
			Logging.log("checkWifi", "Mojo call error - wifi getstatus");
			this.isWifiEnabled = false;
		}.bind(this),
		onComplete: function() {
			this.startTest(this.memory);
		}.bind(this)
	});
}

AutomatedtestsAssistant.prototype.checkAirplaneMode = function() {
	var airplaneRequest = new Mojo.Service.Request("palm://com.palm.systemservice", { 
		method: 'getPreferences',
		parameters: {"subscribe":false,"keys":["airplaneMode"]},
		onSuccess: function(response) {
			if(response.airplaneMode)
				this.sceneAirplane();
			else if(this.deviceHasWifi)
				this.checkWifi();
			else
				this.startTest(this.memory);
		}.bind(this),
		onFailure: function() {
			Logging.log("checkAirplaneMode", "Mojo call error - systemservice getPreferences");
			this.checkWifi();
		}.bind(this)
	});
}

AutomatedtestsAssistant.prototype.checkWifi = function() {
	var wifiRequest = new Mojo.Service.Request('palm://com.palm.wifi', {
		method: 'getstatus',
		parameters: {"subscribe":false},
		onSuccess: function(response) {
			if(response.status == "serviceDisabled")
				this.sceneWifi();
			else {
				this.isWifiEnabled = true;
				this.startTest(this.memory);
			}
		}.bind(this),
		onFailure: function() {
			Logging.log("checkWifi", "Mojo call error - wifi getstatus");
			this.isWifiEnabled = false;
			this.startTest(this.memory);
		}.bind(this)
	});
}

AutomatedtestsAssistant.prototype.memoryTest = function()
{
	if(this.deviceHasWifi && this.isWifiEnabled)
		 this.controller.get('memTextNo').update( $L("Test 1 of 4") );
	else
		 this.controller.get('memTextNo').update( $L("Test 1 of 3") );
	
	this.request[this.request.length] = new Mojo.Service.Request('palm://com.palm.crotest', { 
		method: 'MemoryTest', 
		parameters: {}, 
		onSuccess: function(response) {
			if(response.malloc && response.xor && response.file) {
				Logging.log("Memory", "success");
			}

			if(!(response.malloc)) {
				Logging.log("Memory", "malloc error");
				QuickTestResults.setMemoryResult(1);
			}

			if(!(response.xor)) {
				Logging.log("Memory", "xor error");
				QuickTestResults.setMemoryResult(2);
			}
			
			if(!(response.file)) {
				Logging.log("Memory", "file error");
				QuickTestResults.setMemoryResult(3);
			}
		}.bind(this),
		onFailure: function() {
			Logging.log("Memory", "Mojo call error - crotest MemoryTest");
			QuickTestResults.setMemoryResult(100);
		}.bind(this),
		onComplete: function() {
			if(this.isWifiEnabled)
				this.startTest(this.wifi);
			else {
				Logging.log("Wifi", "Skipping WiFi tests");
				this.startTest(this.bluetooth);
			}
		}.bind(this)
	});
}

AutomatedtestsAssistant.prototype.wifiTest = function() {
	this.controller.get('wifiTextNo').update( $L("Test 2 of 4") );
	
	this.request[this.request.length] = new Mojo.Service.Request('palm://com.palm.wifi', {
		method: 'getstatus',
		parameters: {'subscribe': false},
		onSuccess: function(response) {
			if(response.status != "serviceDisabled") {
				var interface = undefined;
				var gateway = undefined;
				var ipAddress = undefined;

				if(response.ipInfo) {
					interface = response.ipInfo.interface;
					gateway = response.ipInfo.gateway;
					ipAddress = response.ipInfo.ip;
				}

				this.request[this.request.length] = new Mojo.Service.Request('palm://com.palm.wifi', {
					method: 'getinfo',
					parameters: {},
					onSuccess: function(response) {
						if(response.wifiInfo && this.macAddressRegExp.match(response.wifiInfo.macAddress)) {
							if(!interface || !gateway || !ipAddress) {
								Logging.log("Wi-Fi", "valid MAC, not connected to network");
								QuickTestResults.setWifiResult(25);
								this.startTest(this.bluetooth);
							}
							else if(this.ipAddressRegExp.test(ipAddress)) {
								this.request[this.request.length] = new Mojo.Service.Request('palm://com.palm.crotest', {
									method: 'WifiInfo',
									parameters: {'interface':interface,'gateway':gateway},
									onSuccess: function(response) {
										if(response.reachGateway == "true") {
											Logging.log("Wi-Fi", "success");
										}
										else {
											Logging.log("Wi-Fi", "ping error");
											QuickTestResults.setWifiResult(1);
										}
									}.bind(this),
									onFailure: function() {
										Logging.log("Wi-Fi", "Mojo call error - crotest WifiInfo");
										QuickTestResults.setWifiResult(100);
									}.bind(this),
									onComplete: function() {
										this.startTest(this.bluetooth);
									}.bind(this)
								});
							}
							else {
								Logging.log("Wi-Fi", "invalid IP address");
								QuickTestResults.setWifiResult(2);
								this.startTest(this.bluetooth);
							}
						}
						else {
							Logging.log("Wi-Fi", "invalid MAC address");
							QuickTestResults.setWifiResult(3);
							this.startTest(this.bluetooth);
						}
					}.bind(this),
					onFailure: function() {
						Logging.log("Wi-Fi", "Mojo call error - wifi getinfo");
						QuickTestResults.setWifiResult(100);
						this.startTest(this.bluetooth);
					}.bind(this)
				});
			}
			else {
				Logging.log("Wi-Fi", "Wi-Fi disabled");
				QuickTestResults.setWifiResult(1000);
				this.startTest(this.bluetooth);
			}
		}.bind(this),                                                                                                                           
                onFailure: function() {                                                                                                                 
			Logging.log("Wi-Fi", "Mojo call error- wifi getstatus");
			QuickTestResults.setWifiResult(100);                                                                                  
                        this.startTest(this.bluetooth);                                                                                                 
                }.bind(this)                                                                                                                            
        });                                                                                                                                             
}             

AutomatedtestsAssistant.prototype.bluetoothTest = function() {
	if(this.deviceHasWifi && this.isWifiEnabled)
		 this.controller.get('btTextNo').update( $L("Test 3 of 4") );
	else
		 this.controller.get('btTextNo').update( $L("Test 2 of 3") );
	var keyStr = "com.palm.properties.BToADDR";
	this.request[this.request.length] = new Mojo.Service.Request('palm://com.palm.preferences/systemProperties', { 
		method: 'getSysProperty', 
		parameters: {'key': keyStr}, 
		onSuccess: function(response) {
			
			
			if(this.macAddressRegExpUp.test(response[keyStr])) {
				Logging.log("Bluetooth", "success");
				
			}
			else {
				Logging.log("Bluetooth", "invalid MAC address");
				QuickTestResults.setBluetoothResult(1);
			}
		}.bind(this),
		onFailure: function() {
			Logging.log("Bluetooth", "Mojo call error - bluetooth systemProperties/getSysProperty");
			QuickTestResults.setBluetoothResult(100); 
		}.bind(this),
		onComplete: function() {
			this.enableDim();
			if(this.isModemEnabled)
				this.startTest(this.modem);
			else {
				Logging.log("Modem", "Skipping Modem tests");
				QuickTestResults.getNextScene(this.controller.stageController);
			}
		}.bind(this)
	});
}

AutomatedtestsAssistant.prototype.modemTest = function() {
	if(this.deviceHasWifi && this.isWifiEnabled)
		 this.controller.get('modemTextNo').update( $L("Test 4 of 4") );
	else
		 this.controller.get('modemTextNo').update( $L("Test 3 of 3") );
	this.request[this.request.length] = new Mojo.Service.Request('palm://com.palm.connectionmanager', { 
		method: 'getstatus', 
		parameters: {'subscribe': false}, 
		onSuccess: function(response) {
			if(response.wan && response.wan.state != "disconnected") {
				if(this.ipAddressRegExp.test(response.wan.ipAddress)) {
					Logging.log("Modem", "success");
				}
				else {
					Logging.log("Modem", "invalid IP address");
					QuickTestResults.setModemResult(1);
				}
				QuickTestResults.getNextScene(this.controller.stageController);
			}
			else {
				this.wanRequest = new Mojo.Service.Request('palm://com.palm.wan', {                                              
					method: 'getstatus',                                                                                    
					parameters: {'subscribe': true},                                       
					onSuccess: function(response) {
						if(response.networktype && response.networktype == "none") {
							Logging.log("Modem", "No SIM");
							QuickTestResults.setModemResult(1000);
							this.wanRequest.cancel();
							this.wanRequest = undefined;

							QuickTestResults.getNextScene(this.controller.stageController);
						}
						else if(response.networktype) {
							Logging.log("Modem", "No data connection");
							QuickTestResults.setModemResult(20);
							this.wanRequest.cancel();
							this.wanRequest = undefined;

							QuickTestResults.getNextScene(this.controller.stageController);
						}
					}.bind(this),                                                               
					onFailure: function(response) {
						Logging.log("Modem", "Mojo call error - wan getstatus");
						QuickTestResults.setModemResult(100);
						QuickTestResults.getNextScene(this.controller.stageController);
					}.bind(this)
				});
			}
		}.bind(this),
		onFailure: function() {
			Logging.log("Modem", "Mojo call error - connectionmanager getstatus");
			QuickTestResults.setModemResult(100);
			QuickTestResults.getNextScene(this.controller.stageController);
		}.bind(this)
	});
}

