/* Copyright 2009 Palm, Inc.  All rights reserved. */

var CustomizationAssistant = Class.create({
	
	spinner: 'activity-spinner',
	
	spinning: false,
	
	spinnerAttrs: {
		spinnerSize: Mojo.Widget.spinnerLarge
	},
	
	initialize: function() {
		Mojo.Log.info("------------- initialize -----------");
		FirstUseUtil.addDashboardBig($('target'));
		this.checkSIMTimer = setTimeout(this.checkSIM.bind(this), 30000);	
	},
	
	setup: function() {
		$('target').addEventListener(Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
		Mojo.Log.info("------------- setup -----------");
		// Listen to ## key presses
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
		
		this.controller.setupWidget(this.spinner, this.spinnerAttrs, {});
	},
	
	activate: function() {
		this.spinning = true;
		$(this.spinner).mojo.start();
		this.timer = setTimeout(this.sendRequest.bind(this), 2000);
	},
	
	sendRequest: function() {
		if(this.timer) {
			clearTimeout(this.timer);
		}
		this.custRequest = AppAssistant.accountService.populateDefaults(Account.language, Account.country,
								this.readStatus.bind(this), this.errorStatus.bind(this));
		this.localeRequest = AppAssistant.accountService.setLocale(Account.language, Account.country);
		this.regionRequest = AppAssistant.accountService.setRegion(Account.regionCountryCode, Account.regionCountryName);
	},
	
	readStatus: function(response) {
		Mojo.Log.info("------------- read populate defaults response -----------%o", Object.toJSON(response));
		this.checkSIM();
	},
	
	errorStatus: function (response) {
		Mojo.Log.error("------------- error in populating defaults --customization---------%o", Object.toJSON(response));
		// Java crashed, wait till it comes up
		if(response.errorCode && response.errorCode == -1) {
			return;
		}
		this.checkSIM();
	},
	
	checkSIM: function() {
		if(this.custRequest) {
			this.custRequest.cancel();
		}
		if(this.checkSIMTimer) {
			clearTimeout(this.checkSIMTimer);
		}
		if(Account.platformType == "") {
			this.platformRequest = AppAssistant.accountService.getPlatformType(
							this.readPlatformType.bind(this), 
							this.platformQueryError.bind(this));	
		} else {
			this.performNextAction();
		}	
	},
	
	readPlatformType: function(response) {
		Mojo.Log.info("What is the reponse for platform query? %o ", $H(response));
		if(response.returnValue == false) {
			Mojo.Log.error("Telephony is not ready yet");
			return;
		}
		Account.platformType = response.extended.platformType;
		Mojo.Log.info("Platform type = %s", Account.platformType);
		this.performNextAction();
	},
	
	performNextAction: function() {
				
		var platformType = Account.platformType.toLowerCase();
		Mojo.Log.info("perform next action = %s ", platformType);
		if(platformType == 'gsm')  {
			this.checkSIMStatus();
		} else if (platformType == "cdma") {
			
			if(cdmaType == "otasp") {
				if((!isActivated) || (RoamUtil.enableRoaming() === true && prlUpdateDone === false)) {
					Mojo.Controller.stageController.pushScene("otasp-intro");
					return;
				}	
			}
			//If user has already seen phone activated scene and declicustomizationned terms and conditions,
			// we show the language scene. On resuming, we don't want to show phone activation scene again
			if(isActivated) {
				if (Account.action == 'decline') {
					Account.action = '';
					Mojo.Controller.stageController.pushScene("terms");
				} else {
					Mojo.Controller.stageController.pushScene("provision");					
				}	
				return;
			} 
			Mojo.Controller.stageController.pushScene("provision");
		} else {
			Mojo.Log.error("Telephony is not ready yet");
			Mojo.Controller.stageController.pushScene('error');
		}
	},
	
	getDeviceLockValue: function () {
		this.locktype = undefined;
		this.lockRequest = AppAssistant.gsmService.getDeviceLockValue(this.readDeviceLockValue.bind(this),
									this.errorDeviceLockValue.bind(this));
	},
	
	readDeviceLockValue: function (response) {
		if(!response) {
				Mojo.Controller.stageController.pushScene('error');
				return;
		 }
		 if (response.extended) {
		 	var keys = Object.keys(response.extended);
		 	Mojo.Log.info("------------------------- keys ------------------%j", keys);
		 	if (keys.size() > 1) {
				for (var i = 0; i < keys.size(); i++) {
					if (response.extended[keys[i]] == true) {
						this.lock = "devicelock";
						this.unblock = true;
						this.locktype = keys[i];
						break;
					}
				}
			}
			else if (keys.size() == 1) {
					this.lock = "devicelock";
					this.unblock = response.extended[keys[0]];
					this.locktype = keys[0];
			} else {
				if(this.doUnlock === true) {
					return;
				}
				Mojo.Controller.stageController.pushScene('error');
				return;
			}
		 	if (this.locktype != undefined) {
				this.showTermsConditions();
				if(this.lockRequest) {
					this.lockRequest.cancel();
				}
				this.lockRequest = undefined;
				this.doUnlock = true;
		 		this.displayRequest = AppAssistant.gsmService.displayDeviceLock(this.locktype, this.unblock);
		 		// query for emergency numbers, since this event indicates the simcard is ready for reading
				FirstUseUtil.getEmergencyNumbers();
			}
		}
			  
	},
	
	errorDeviceLockValue: function (response) {
		Mojo.Log.error("---------- Could not read device lock mode --------------%j", response);
		Mojo.Controller.stageController.pushScene('error');
	},
		
	checkSIMStatus: function() {
		this.simStatusRequest = AppAssistant.accountService.getSIMStatus(this.readSIMStatus.bind(this), this.simError.bind(this), true);			
	},
	
	getNetworkStatus: function () {
		this.networkRequest = AppAssistant.accountService.getNetworkStatus(this.readNetworkStatus.bind(this), this.errorNetworkStatus.bind(this));
	},
	
	readNetworkStatus: function (response) {
		Mojo.Log.info("--------------------------- readNetworkStatus ---------------------------%o", $H(response.extended));
		if(response.extended && response.extended.state === "service") {
			if(this.networkRequest) {
				this.networkRequest.cancel();
			}
			this.getFDNStatus();
		} else {
			//TODO
		}
	},

	errorNetworkStatus: function (response) {
		Mojo.Log.error("--------------------------- errorNetworkStatus ---------------------------%o", $H(response));
		// Show error
		isCamped=false;	
		checkDatabase();
	},
	
	displayPin1Lock: function() {      
        var request = FirstUseUtil.displayPin1Lock();
    },
	
	displayPuk1Lock: function() {
        var request = FirstUseUtil.displayPuk1Lock();
    },	
	
	processSIMStatus: function (status) {
		Mojo.Log.info("processSIMStatus - push scene ------------ ");
		if (status == "simnotfound") {
			Mojo.Controller.stageController.pushScene("nosim");
		}
		else if (status == "siminvalid") {
			Mojo.Controller.stageController.pushScene("invalidsim");
		}
		else if(status == "pinrequired") {
			this.showTermsConditions();
			this.displayPin1Lock();
		}
		else if(status == "simready"){
			this.getNetworkStatus();
		}
		else if(status == "pukrequired") {
			this.displayPuk1Lock();
		} 
		else if(status == "unknown") {
			this.getDeviceLockValue();
		} 	
	},
	
	getFDNStatus: function () {
		this.fdnStatusRequest = AppAssistant.accountService.getFDNStatus(this.readFDNStatus.bind(this), this.fdnError.bind(this));
	},
	
	readFDNStatus: function(response) {
		if(response && response.extended && response.extended.enabled === true) {
			this.termsTimer = setTimeout(this.showTerms.bind(this), 3000);
			var request = FirstUseUtil.displayFDNUnLock();
		} else {
			this.showTermsConditions();
		}
	},
	
	showTerms: function () {
		clearTimeout(this.termsTimer);
		this.showTermsConditions();	
		
	},
	
	fdnError: function(response) {
		Mojo.Log.error("----------- Error in getting fdn status ----------------%j", response);
		this.showTermsConditions();
	},
	
	readSIMStatus: function(response) {
		if(response.returnValue == true) {
			var status = response.extended.state;
			Mojo.Log.info("SIM Status = %s", status);
			this.processSIMStatus(status);
		}
	},
	
	simError: function(response) {
		Mojo.Log.error("SIM error %j ", response);
		Mojo.Controller.stageController.pushScene('error');
	},
	
	platformQueryError: function (response) {
		Mojo.Log.error("Telephony platform query error %j ", response);
		Mojo.Controller.stageController.pushScene('error');
	},
	
	showTermsConditions:function() {
		Mojo.Controller.stageController.pushScene('terms');
	},
		
	deactivate: function() {
		if (this.timer) {
			clearTimeout(this.timer);
		}	
		if(this.checkSIMTimer) {
			clearTimeout(this.checkSIMTimer);
		}
		$(this.spinner).mojo.stop();
		this.spinning = false;
	}	
});
