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

var SetpinAssistant = Class.create({
	
	// TODO: remove this mapping once the framework provides
	// a more robust method of mapping/converting a character to a number
	numericMap: {
		e:'1',r:'2',t:'3',
		d:'4',f:'5',g:'6',
		x:'7',c:'8',v:'9',
			'@':'0',
		
		1:'1',2:'2',3:'3',
		4:'4',5:'5',6:'6',
		7:'7',8:'8',9:'9',
			  0:'0'
	},
	
	initialize: function(policy, onSuccess) {
		this.policy = policy;
		this.onSuccess = onSuccess;
	},
	
  	setup: function() {
		
		this.dsAttributes = {
			modelProperty: 'pin',
		};
		this.pinModel = {
		    'pin': '',
			disabled: true
		};
		this.controller.setupWidget('pinfield', this.dsAttributes, this.pinModel);
		
		this.bigTitleElem = this.controller.get('pin-title-big');
		this.smallTitleElem = this.controller.get('pin-title-small');
		Mojo.Log.info("-----------> this.policy=%j", this.policy);
		
		if (this.policy.password.minLength <= 1) {
			this.pinInstructions = SetpinAssistant.kNUMERIC;
		} else {
			this.pinInstructions = SetpinAssistant.kMINLENGTH.interpolate(this.policy.password);
		}
		this.smallTitleElem.innerHTML = this.pinInstructions;
		
		this.controller.listen('zero_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '0'));
		this.controller.listen('one_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '1'));
		this.controller.listen('two_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '2'));
		this.controller.listen('three_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '3'));
		this.controller.listen('four_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '4'));
		this.controller.listen('five_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '5'));
		this.controller.listen('six_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '6'));
		this.controller.listen('seven_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '7'));
		this.controller.listen('eight_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '8'));
		this.controller.listen('nine_button', Mojo.Event.tap, this.onNumberPress.bindAsEventListener(this, '9'));
		this.controller.listen('backspace', Mojo.Event.tap, this.onDeletePress.bindAsEventListener(this));
	
		this.controller.listen('cancel_pin', Mojo.Event.tap, this.cancel.bindAsEventListener(this));
		this.controller.listen('done_pin', Mojo.Event.tap, this.done.bindAsEventListener(this));
			
		this.pinKeyPressHandler = this.onPinKeyPress.bindAsEventListener(this);	
		Mojo.listen(this.controller.sceneElement, Mojo.Event.keypress, this.pinKeyPressHandler);
		
		var appMenuModel = {
	        visible: true,
	        items: [Mojo.Menu.editItem,{label:$L('Help'), command:Mojo.Menu.helpCmd}
	            ]
	        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);		
		this.clearPinField(true);
  	},
	
	
	cleanup:function(){

	},
	
	handleCommand: function(event) {
		if(!event)
			return;
		if (event.type == Mojo.Event.back) {
			this.cancel();
		}
		else if (event.type == Mojo.Event.command) {
			if(event.command == Mojo.Menu.helpCmd) {
				MenuController.showHelp();
			}
		}	
	},
			
	cancel: function() {
		// Clear out the policy since the user cancelled
		this.removePolicy();
		this.popScene('back');
	},

	removePolicy: function() {
		this.controller.serviceRequest(SecuritypolicyAssistant.kSystemManager, {
			method: 'removeSecurityPolicy',
			parameters: { id: this.policy.id.toLowerCase() },
			onSuccess: Mojo.doNothing,
			onFailure: Mojo.doNothing
		});
	},
	
	popScene: function(action) {
		Mojo.Log.info("----------- SetpinAssistant popping with result:", action);
		this.controller.stageController.popScene({ action: action });
	},
	
	done: function() {
		this.testPin();
	},
	
	updatePinField: function(value) {
		
		if (this.pinModel.pin.length >= 29) {
			return;
		}
		if (this.pinModel.pin.length === 0 && !this.firstAttempt) {
			this.smallTitleElem.innerHTML = this.pinInstructions;
		}
		this.pinModel.pin = this.pinModel.pin+value;
		this.controller.modelChanged(this.pinModel, this);
	},
	
	clearPinField: function(clearAll) {
		var len = this.pinModel.pin.length;
		if(clearAll) {
			this.pinModel.pin= '';
			this.controller.modelChanged(this.pinModel, this);
		} else if(len > 0){
			this.pinModel.pin = this.pinModel.pin.slice(0, len - 1);
			this.controller.modelChanged(this.pinModel, this);
		}
	},
  	
	onNumberPress: function(event, number) {
		Event.stop(event);
		
		this.updatePinField(number);
	},
	
	onPinKeyPress: function(event) {
		Event.stop(event);
		var code = event.originalEvent.keyCode;
		var c = String.fromCharCode(code).toLowerCase();
		var numeric = this.numericMap[c];
		
		if(this.retry) {
			this.bigTitleElem.innerHTML = $L('Enter PIN');
			this.smallTitleElem.innerHTML = this.pinInstructions;
			this.retry = false;
		}
		
		if (Mojo.Char.isDeleteKey(code)) {
			this.clearPinField(false);
		}
		else if (Mojo.Char.isEnterKey(code)) {
			this.testPin();
		}
		else if (numeric != null) {
			this.updatePinField(numeric);
		}
	},
	
	onDeletePress: function(event) {
		event.stop();
		this.clearPinField(false /* only clear last */);
	},
	
	
	testPin: function() {
		var doneButton = this.controller.get('done_pin');
		doneButton.disabled = true;
		
		var payload = {passCode: ''};
		payload.passCode = this.pinModel.pin;
		if(!this.firstAttempt) {
			this.firstAttempt = payload;
			this.bigTitleElem.innerHTML = SetpinAssistant.kEnterPinAgain;
			this.smallTitleElem.innerHTML = "";
			this.clearPinField(true);
			doneButton.disabled = false;
		} else {
			if(this.firstAttempt.passCode === payload.passCode) {
				this.controller.serviceRequest(SecuritypolicyAssistant.kSystemManager, {
					method: 'setDevicePasscode', //validate password meets the security policy requirements
					parameters: { passCode: payload.passCode, lockMode: 'pin' },
					onSuccess: this.onPinSuccess.bind(this),
					onFailure: this.onPinError.bind(this),
				});
			} else {
				this.showError(SetpinAssistant.kTryAgain, SetpinAssistant.kPinDoesnotMatch);
				doneButton.disabled = false;
			}
		}
	},
	
	onPinSuccess: function(response) {
		Mojo.Log.info("passwordSuccess %j", response);
		this.onSuccess();
		this.popScene('create');
	},

	onPinError: function(response) {
		Mojo.Log.info("passwordError %j", response);
		this.showError(SetpinAssistant.kTryAgain, SetpinAssistant.kPasswordsNoGoodEnough);

		var doneButton = this.controller.get('done_pin');
		doneButton.disabled = false;
	},
	
	showError: function(bigTitleText, smallTitleText) { 
		this.bigTitleElem.innerHTML = bigTitleText;
		this.smallTitleElem.innerHTML = smallTitleText;
		this.clearPinField(true);
		this.retry = true;
		delete this.firstAttempt;
	},
	
	popScene: function(action) {
		Mojo.Log.info("----------- SetpinAssistant popping with result:", action);
		this.controller.stageController.popScene({ action: action });
	},
});


SetpinAssistant.kMINLENGTH = $L("PIN must be at least #{minLength} numbers");
SetpinAssistant.kNUMERIC = $L("PIN must be numbers");
SetpinAssistant.kEnterPinAgain = $L('Enter PIN Again');
SetpinAssistant.kPasswordsNoGoodEnough = $L("PIN does not meet security requirements");
SetpinAssistant.kTryAgain = $L("Try Again");
SetpinAssistant.kPinDoesnotMatch = $L("PIN doesn't match");
