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

var ProvisionAssistant = Class.create({
	
	initialize: function(){
		
		Mojo.Log.info("init prov asst");
		FirstUseUtil.addDashboardBig($('target'));
		saveCurrentState("provision");
		this.progress = 0;
		this.setTimer = false;
		
		// To check if cidc session is started, if it's not started, time out provisioning
		this.cidcSession = false;
	},
	
	setup: function() {
		Mojo.Log.info("set up prov asst");
		
		$('target').addEventListener(Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
				
		// Listen to ## key presses
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
				
		this.nextModel = {
			buttonLabel : $L('Next'),
			buttonClass: 'palm-button'
		};
		this.controller.setupWidget('showMeTerms', undefined, this.nextModel);
		Mojo.listen(this.controller.get('showMeTerms'), Mojo.Event.tap, this.showMeTerms.bindAsEventListener(this));
		
		if (isActivated) {
			this.provisionComplete();
			return;
		} 
		
		this.deviceIdRequest = AppAssistant.accountService.getDeviceId(
											this.readDeviceId.bind(this), 
											this.deviceIdRequestFailed.bind(this), this.controller);
		
		if((!isActivated) && (activationFailed) && (cdmaType == "otasp")) {
			this.otaspProvisionTotallyFailed(); 	
			return;
		}
		
		if(cdmaType == "otasp") {
			return;
		}
		
		this.tryAgainModel = {
			buttonLabel : $L('Try Again'),
			buttonClass: 'palm-button'
		};
		this.controller.setupWidget('tryAgain', {}, this.tryAgainModel);
		Mojo.listen(this.controller.get('tryAgain'), Mojo.Event.tap, this.cidcActivation.bindAsEventListener(this));
		
			
				
		this.setupProgressBar();
		ProvisionUtil.setScene(this);
				
		if((!isActivated) && (activationFailed)) {
			if (!activationErrorCode.empty()) {
				this.provisionTotallyFailed();
			} else {
				// HFA failed
				this.hfaFailed();
				this.provisionError();
			}	
			return;
		}
		
		this.checkActivationStatus();
				
		//Increased the timeout as each retry could take 1 min and 30 secs
		new PeriodicalExecuter(function(pe) {
			Mojo.Controller.stageController.delegateToSceneAssistant("timeOutProvision", pe);
		}, 960);
		
		
	},
	
	readDeviceId: function (response) {
		if(response.deviceId) {
			Account.deviceId = response.deviceId;
			this.deviceId = response.deviceId.gsub('MEID:', '');
			$('meidText').update(this.deviceId);
			$('cidcText').update(this.deviceId);
			if (this.deviceIdRequest) {
				this.deviceIdRequest.cancel();
			}
		} 
	},
	
	deviceIdRequestFailed: function(response) {
		// Try again
		this.deviceIdRequest = AppAssistant.accountService.getDeviceId(
											this.readDeviceId.bind(this), 
											this.deviceIdRequestFailed.bind(this), this.controller);
	},
		
	setupProgressBar: function() {
		this.attr = {
			cancellable: true,
			modelProperty: 'progress'
		};
		this.model = {
			progress: 0
		};
		this.progress = 0;
		this.controller.setupWidget('progressBar', this.attr, this.model);
		$('provisionProgress').show();
		
		if (FirstUseUtil.carrierShortName.blank()) {
			this.getCarrierName();
		}
		else {
			this.updateWaitMessageText();
		}	
		$('waitMessage').show();
	},
	
	updateWaitMessageText: function () {
		// Doing something by comparing the carrier short name will work only for CDMA
		// It will not work for CDMA as user can have a SIM from a different carrier than the one 
		// for which the device is flashed
		if(FirstUseUtil.carrierShortName === "Bell Mobility") {
			$('waitMessageText').update($L("Activating phone..."));
		} else {
			$('waitMessageText').update($L("Waiting to retry..."));
		}
	},
		
	getCarrierName: function () {
		this.carrierRequest = AppAssistant.accountService.getCarrierName(
				this.readCarrierName.bind(this));
	},
	
	readCarrierName: function(response) {
		Mojo.Log.info("----------------- readCarrierName----------------%j", response);
					
		if(response.returnValue && response.returnValue == true) {
			FirstUseUtil.carrierShortName = response.shortName;
			if (FirstUseUtil.carrierShortName) {
				if(this.carrierRequest) {
					this.carrierRequest.cancel();
				}
				this.updateWaitMessageText();
			}	
		}
	},	
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.back) {
			event.preventDefault();
			event.stopPropagation();
			// Block back if it is otasp
			if(cdmaType === 'otasp') {
				return;
			}
			Mojo.Log.info("----------- Popping this scene to show language ------------");
			Mojo.Controller.stageController.popScene();
			Mojo.Controller.stageController.pushScene("language");
		}	
	},
	
	timeOutProvision: function(pe) {
		Mojo.Log.info("Timeout provision called");
		pe.stop();
		if((!isActivated) && (!this.cidcSession)) {
			this.provisionTotallyFailed();
			return;
		} 
	},	
	
	provisionDevice: function () {
		Mojo.Log.info("provisionDevice");
				
		$('provisionFailed').hide();
		$('provisionDone').hide();
		$('provisionTotallyFailed').hide();
    $('buttonBottomFade').hide();	
	},
	
	activationDone: function () {
		this.progress = 1;
		this.updateProgress();
		clearTimeout(this.updater);
		ProvisionUtil.resetScene();
		this.completer = window.setTimeout(this.provisionComplete.bind(this), 1000);
	},
	
	hfaFailed: function () {
		attemptCount = 1;
		this.cidcSession = true;
	},
	
	showHfaFailed: function () {
		this.hfaFailed();
		clearTimeout(this.updater);
		this.progress = 1;
		this.updateProgress();
		this.completer = window.setTimeout(this.provisionError.bind(this), 500);
	},
	
	cidcFailed: function() {
		this.completeCidcProgressBar();	
	},
	
	checkActivationStatus: function() {
		Mojo.Log.info("check if activated?", isActivated, "session status? ", sessionStatus);
				
		if (sessionStatus == "NetworkRetry") {	
			this.setTimer = false;
			clearTimeout(this.updater);
			this.completeProgressBar();
		}
		else if ((sessionStatus == "Waiting") && (!this.cidcSession)){
			this.setTimer = false;
			clearTimeout(this.updater);
			this.updateProgressBar();					
			$('waitMessage').show();
			$('retryMessageDiv').hide();	
		}
		else if ((sessionStatus == "Busy") && (!this.cidcSession)){
			if (this.setTimer == false) {
				clearTimeout(this.updater);
				this.updateProgressBar();
				$('retryMessageDiv').hide();
			}		
		}
	},
	
	showRetryMessage: function() {
		if (attemptCount > 0) {
			var data = {
				num: attemptCount
			};
			var localizedText = $L("Retrying (Attempt #{num} of 5)").interpolate(data);
			
			$('waitMessage').hide();
			$('retryMessageDiv').show();
			$('retryMessage').update(localizedText);
		}
	},
	
	updateProgressBar: function() {
		
		$('progressBar').hide();
		
		if (this.setTimer == false) {
			Mojo.Log.info("---------------- Update progress bar -------------",this.setTimer);
			this.setTimer = true;
			this.progress = 0.01;
			this.updateProgress();
			$('progressBar').show();
			this.controller.showWidgetContainer($('progressBar'));
			this.showRetryMessage();
			this.updater = window.setInterval(this.updateProgress.bind(this), 1000);	
		}	
	},
	
	updateCidcProgressBar: function() {
				
		$('progressBar').hide();
		if (this.setTimer == false) {
			Mojo.Log.info("---------------- Update cidc progress bar -------------",this.setTimer);
			
			this.setTimer = true;
			this.progress = 0.01;
			this.updateProgress();
			$('progressBar').show();
			this.controller.showWidgetContainer($('progressBar'));
			this.showCidcRetryMessage();
			this.updater = window.setInterval(this.updateProgress.bind(this), 50);	
		}	
	},
	
	showCidcRetryMessage: function() {
		if (attemptCount > 0) {
			var data = {
				num: attemptCount
			};
			var localizedText = $L("Retrying (Attempt #{num} of 3)").interpolate(data);
			$('waitMessage').hide();
			$('retryMessageDiv').show();
			$('retryMessage').update(localizedText);
		}
	},
	
	completeProgressBar: function () {
		this.model.progress = 1.0;
		this.controller.modelChanged(this.model);
		this.progressReseter = window.setTimeout(this.updateProgressBar.bind(this), 500);	
	},
	
	updateProgress: function() {
		Mojo.Log.info("------------------------- Update progress ------------------------", this.model.progress);
		if(this.progress > 1.0) {
			clearTimeout(this.updater);
		}
		this.progress = this.progress + 0.01;
		this.model.progress = this.progress;
		this.controller.modelChanged(this.model);
	},
	
	cidcActivation: function () {
		this.tryAgainModel.disabled = true;
		this.controller.modelChanged(this.tryAgainModel);
				
		$('provisionFailed').hide();
		$('provisionDone').hide();
		$('provisionTotallyFailed').hide();
		$('waitMessage').hide();
		$('retryMessageDiv').hide();
    $('buttonBottomFade').hide();
				
		this.setTimer = false;
		$('provisionProgress').show();
		this.updateCidcProgressBar();
		this.cidcRequest = AppAssistant.accountService.cidcProvision(this.cidcSuccess.bind(this), 
													this.cidcError.bind(this));
	},
	
	completeCidcProgressBar: function () {
		clearTimeout(this.updater);
		this.model.progress = 1.0;
		Mojo.Log.info("Progress to show completeCidcProgressBar-----------------------------------", this.progress);
		this.controller.modelChanged(this.model);
		this.cidc = window.setTimeout(this.cidcShowStatus.bind(this), 1000);	
	},
	
	cidcSuccess: function (response) {
		Mojo.Log.info("provision status = %o", $H(response));
		if(response.returnValue == false) {
			isActivated = false;
			activationFailed = true;	
			this.completeCidcProgressBar();
		}  
	}, 
	
	cidcShowStatus: function (response) {
		Mojo.Log.info("-------------- Show cidc status ----------------------");
		Mojo.Log.info("-------------- isActivated, activationFailed, attemptCount ---------------------------", isActivated, activationFailed, attemptCount);
		Mojo.Log.info("provision error code ================= %o", activationErrorCode);
		if (!activationErrorCode.empty()) {
			this.provisionTotallyFailed();
			return;
		}
		if(isActivated == false && activationFailed == true) {
			if (attemptCount <= 4) {
				this.tryAgainModel.disabled = false;
				this.controller.modelChanged(this.tryAgainModel);
				this.provisionError();
			}	
		}  
	}, 
	
	cidcError: function (response) {
		Mojo.Log.error("provision error = %o", $H(response));
		isActivated = false;
		activationFailed = true;	
		this.completeCidcProgressBar();
	},
	
	provisionError: function () {
		$('provisionProgress').hide();
		$('provisionDone').hide();
		$('provisionFailed').show();
		$('buttonBottomFade').show();
		$('provisionTotallyFailed').hide();
		
		if (FirstUseUtil.carrierUrl.blank()) {
			this.getCarrierUrl();
		} else {
			this.updateCarrierUrlText();
		}	
	},
	
	getCarrierUrl: function () {
		this.carrierUrlRequest = new Mojo.Service.Request(NovaAccountService.systemServiceIdentifier, {
				method: 'getPreferences',
				parameters: {"keys":["carrierUrl"]},
				onSuccess: this.readCarrierUrl.bind(this),
				onFailure: this.readCarrierUrl.bind(this)
		});
	},
	
	readCarrierUrl: function(response){
		if(response.carrierUrl) {
			if (Object.isString(response.carrierUrl)) {
				FirstUseUtil.carrierUrl = response.carrierUrl.gsub("\"", "");
			} else {
				FirstUseUtil.carrierUrl = response.carrierUrl;
			}	
		}
		
		if(response.errorCode == -1) {
			FirstUseUtil.carrierUrl = $L("your carrier's website");
		}	
		this.updateCarrierUrlText();
	},
	
	updateCarrierUrlText: function () {
		this.info = $L("You may need to activate your phone by going to #{carrierUrl}.").interpolate({
					carrierUrl: FirstUseUtil.carrierUrl
				});
		this.controller.get('carrierUrlText').update(this.info);
	},
	
	provisionComplete: function () {
		$('provisionProgress').hide();
		$('provisionFailed').hide();
		$('provisionTotallyFailed').hide();
		$('provisionDone').show();
		$('buttonBottomFade').show();
		if(cdmaType === "omadm") {
			setRoamMode('any');
		}
	},
	
	getCarrierInfo: function () {
		this.carrierInfoRequest = new Mojo.Service.Request(NovaAccountService.systemServiceIdentifier, {
				method: 'getPreferences',
				parameters: {"keys":["carrierString", "activationCareNumber"]},
				onSuccess: this.readCarrierInfo.bind(this),
				onFailure: this.readCarrierInfo.bind(this)
		}, true);
	},
	
	readCarrierInfo: function (response) {
		if(!response.errorCode) {
			this.carrierInfoRequest.cancel();
		}
		if(response.carrierString) {
			if (Object.isString(response.carrierString)) {
				FirstUseUtil.carrierString = response.carrierString.gsub("\"", "");
			} else {
				FirstUseUtil.carrierString = response.carrierString;
			}	
		}
			
		if(response.activationCareNumber) {
			if (Object.isString(response.activationCareNumber)) {
				FirstUseUtil.activationCareNumber = response.activationCareNumber.gsub("\"", "");
			} else {
				FirstUseUtil.activationCareNumber = response.activationCareNumber;
			}
		}
		this.updateCallInfo();
	},
	
	updateCallInfo: function () {
		this.callInfo = $L(" Please dial #{carrierString} Customer Service at #{activationCareNumber} from a different phone.").interpolate({
					carrierString: FirstUseUtil.carrierString,
					activationCareNumber: FirstUseUtil.activationCareNumber
				});
		this.controller.get('callInfo').update(this.callInfo);
	},
	
	provisionTotallyFailed: function() {
		$('provisionProgress').hide();
		$('provisionFailed').hide();
		$('provisionDone').hide();
		$('provisionTotallyFailed').show();
		$('buttonBottomFade').hide();		
		$('activationErrorCode').update(activationErrorCode);
		
		if(FirstUseUtil.carrierString.blank() || FirstUseUtil.activationCareNumber.blank()) {
			this.getCarrierInfo();
		}  else {
			this.updateCallInfo();
		}
		
		this.notifyRequest = AppAssistant.accountService.notifyProvisioning(
											this.readNotificationStatus.bind(this), 
											this.controller);
	},
	
	otaspProvisionTotallyFailed: function() {
		$('provisionProgress').hide();
		$('provisionFailed').hide();
		$('provisionDone').hide();
		$('provisionTotallyFailed').show();
    $('buttonBottomFade').hide();
				
		if(FirstUseUtil.carrierString.blank() || FirstUseUtil.activationCareNumber.blank()) {
			this.getCarrierInfo();
		}  else {
			this.updateCallInfo();
		}
	},
	
	readNotificationStatus: function (response) {
		if(response.errorCode) {
			Mojo.Log.error("--------- Could not notify provisioning to process NIDC ---------", Object.toJSON(response));
		} else {
			Mojo.Log.error("--------- Notified provisioning to process NIDC ---------", Object.toJSON(response));
		}
	},
	
	showMeTerms: function() {
		Mojo.Controller.stageController.popScene();
		Mojo.Controller.stageController.pushScene('terms');
	}
	
});	
