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

var OtaspProvisionAssistant = Class.create({
	
	spinner: 'activity-spinner',
	
	spinning: false,
	
	spinnerAttrs: {
		spinnerSize: Mojo.Widget.spinnerLarge
	},
	
	initialize: function() {
		this.subscribeToOtaspEvent();
		this.attemptCount = 0;
		FirstUseUtil.addDashboardOtasp($('target'));
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.back) {
			event.preventDefault();
			event.stopPropagation();
		}	
	},	
	
	setup: function(){
				
		// Listen to ## key presses
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
		
		Mojo.Log.info("start spinner now ");		
		this.controller.setupWidget(this.spinner, this.spinnerAttrs, {});	
		
		this.showErrorsModel = {
			buttonLabel : $L('View programming errors'),
			buttonClass: 'palm-button'
		};
		this.controller.setupWidget('showErrors', {}, this.showErrorsModel);
		Mojo.listen(this.controller.get('showErrors'), Mojo.Event.tap, this.showProgrammingErrors.bindAsEventListener(this));
		
		this.getDeviceId();
		this.activateDevice();
	},
	
	activate: function(returnValue){
		if(returnValue && returnValue === 'error') {
			// Don't start spinner
			return;
		}
		this.spinning = true;
		$(this.spinner).mojo.start();
	},
	
	deactivate: function () {
		 this.stopSpinner();
		 this.cancelOtaspEventSubscription();
	},
	
	stopSpinner: function () {
		if (this.spinning) {
			$(this.spinner).mojo.stop();
			this.spinning = false;
		}	
	},	
	
	cleanup: function(event) {
		
	},
	
	subscribeToOtaspEvent: function () {
		this.otaspStatusRequest = AppAssistant.otaspService.subscribeToOtaspEvent(this.readOtaspStatus.bind(this), this.otaspError.bind(this));
	},
	
	cancelOtaspEventSubscription: function () {
		if(this.otaspStatusRequest) {
		 	this.otaspStatusRequest.cancel();
		 }
	},
	
	activateDevice: function () {
		this.programmingMessages = [];
		this.clearOTASPNotification();
		if(this.attemptCount > 0) {
			var data = {
				num: this.attemptCount
			};
			var localizedText = $L("Retrying (Attempt #{num} of 2)").interpolate(data);
			
			this.controller.get('retryMessageDiv').show();
			this.controller.get('retryMessage').update(localizedText);
		} 
		if (!isActivated) {
			this.request = AppAssistant.otaspService.activateDevice(FirstUseUtil.carrierName, activationNumber);
		}
		else if (RoamUtil.enableRoaming() === true && prlUpdateDone === false) {
			this.request = AppAssistant.otaspService.activateDevice(FirstUseUtil.carrierName, prlUpdateNumber);	
		} else {
			prlUpdateDone = true;
			this.showSuccess();
		}	
	},
	
	readOtaspStatus: function (response) {
		Mojo.Log.info("otasp status = %j ", response);
		if (!response.eventOtasp) {
			return;
		}	
		this.sessionStatus = response.eventOtasp.status;
		
		if(this.sessionStatus == "programmingfailed") {
			if(++this.attemptCount < 3) {
				this.timer = setTimeout(this.activateDevice.bind(this), 10000);
			} else {
				if(!isActivated) {
					this.showError();
					activationFailed = true;
				}
				prlUpdateDone = true;
			}
		} else if(this.sessionStatus == "programmingsucceeded") {
			isActivated = true;
			prlUpdateDone = true;
		}
		 
		if(isActivated && prlUpdateDone) {
			this.cancelOtaspEventSubscription();
			this.clearOTASPNotification();
			this.showSuccess();
			return;
		}
		this.handleOTASPNotification(response);
	},
	
	otaspError: function (response) {
		Mojo.Log.error("otasp provision error = %j", response);
		
		activationFailed = true;
		this.showError();
		this.controller.get('showErrors').hide();
	},
	
	showSuccess: function () {
		Mojo.Controller.stageController.pushScene('provision');
	},	
	
	showError: function () {
		this.stopSpinner();
		this.controller.get('otaspProgress').hide();
		this.controller.get('provisionTotallyFailed').show();
		FirstUseUtil.addDashboardBig($('target'));
		$('target').addEventListener(Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
		this.updateCallInfo();
	},
	
	getDeviceId: function () {
		this.deviceIdRequest = AppAssistant.accountService.getDeviceId(
											this.readDeviceId.bind(this), 
											this.deviceIdRequestFailed.bind(this), this.controller);
	},
	
	readDeviceId: function (response) {
		if(response.deviceId) {
			Account.deviceId = response.deviceId;
			this.deviceId = response.deviceId.gsub('MEID:', '');
			this.controller.get('meidText').update(this.deviceId);
		} 
	},
	
	deviceIdRequestFailed: function(response) {
		// Try again
		this.getDeviceId();
	},
	
	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);
	},
	
	showProgrammingErrors: function () {
		Mojo.Controller.stageController.pushScene('otasp-error', this.programmingMessages);
	},
	
	clearOTASPNotification: function () {
		this.controller.get('otaspUpdateText').update("");
		this.controller.get('otaspUpdateIcon').style.display = "none";
	},
	
	handleOTASPNotification: function(msg) {				
		if((!msg.eventOtasp) || (!msg.eventOtasp.status)) {
			return;
		}	
		msg = msg.eventOtasp.status;
		var dispMsg = OtaspMessages.otaspNotifications[msg] || msg.unescapeHTML();
		// Please don't add anything before this
		this.programmingMessages.push({
			"message": $L(dispMsg)
		});
		if (this.controller.get('otaspUpdateIcon')) {
			this.controller.get('otaspUpdateIcon').style.display = "block";
		}	
		
		if (this.controller.get('otaspUpdateText')) {
			this.controller.get('otaspUpdateText').update($L(dispMsg));
		}
	}
	
});	