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

var ResetPasswordAssistant = Class.create({
	
	initialize : function(sceneAssistant, myProfile) {
		this.myProfile = myProfile;
		this.sceneAssistant = sceneAssistant;
		this.controller = sceneAssistant.controller;
		this.usrpwd_confirm_password_hintText = $L("confirm password...");
		this.usrpwd_password_hintText = $L("enter password...");
		this.usrpwd_confirm_message = $L("Password changed")
	}, //sceneAssistant imported into current context, as well as its' controlelr
	
	handleCommand: function (event) {
		if (event.type == Mojo.Event.back) { //event of type back (???)
			Mojo.log.info("back pressed");
			this.widget.mojo.close();        //close this widget (change-password-assistant.js) is part of one widget
			event.preventDefault();
			event.stop(); //stop the event  (why must it be stopped?)
		}
	},
	activate: function(){
		this.controller.get("newPassword").mojo.focus();
	},
	
	setup : function (widget){
		this.widget = widget;
		this.clearErrorMessages();
		
		this.acctPasswordAttr = {
			hintText: this.usrpwd_password_hintText,
			modelProperty: 'original',
			focus: true,
			focusMode: Mojo.Widget.focusSelectMode,
			maxLength: ProfileUtil.MAXPASSWORDLENGTH,
			changeOnKeyPress: true,
			requiresEnterKey: true
		};
		this.acctPasswordModel = {
			'original' : ''
		};
		
		this.acctPasswordAttr.charsAllow = ProfileUtil.filterSpace.bind(this);
		this.controller.setupWidget('newPassword', this.acctPasswordAttr, this.acctPasswordModel);
		
		this.verifyPasswordAttr = {
			hintText: this.usrpwd_confirm_password_hintText,
			modelProperty: 'verify',
			maxLength: ProfileUtil.MAXPASSWORDLENGTH,
			focusMode: Mojo.Widget.focusSelectMode,
			className: ' ',
			changeOnKeyPress: true,
			requiresEnterKey: true,
			focus: false
		};
		this.verifyPasswordModel = {
			'verify' : ''
		};
		
		this.verifyPasswordAttr.charsAllow = ProfileUtil.filterSpace.bind(this);
		this.controller.setupWidget('confirmPassword', this.verifyPasswordAttr, this.verifyPasswordModel);
		this.controller.get('newPassword').observe(Mojo.Event.propertyChange, this.passwordChanged.bind(this));
		this.controller.get('confirmPassword').observe(Mojo.Event.propertyChange, this.verifyPasswordChanged.bind(this));
		
		this.buttonAttr = {
			disabledProperty: 'disabled'
		};
		this.buttonModel = {
			disabled: true,
			buttonLabel : $L('Done'),
			buttonClass: 'palm-button'
		}; 
		
		this.controller.setupWidget('submitChangePassword', this.buttonAttr, this.buttonModel);
		Mojo.listen(this.controller.get('submitChangePassword'), Mojo.Event.tap, this.changePassword.bindAsEventListener(this));
	},
	
	toggleDisabled: function(){
			if ((this.acctPasswordModel.original.length > 0) &&
				(this.verifyPasswordModel.verify.length > 0)) {
					this.buttonModel.disabled = false;
					this.controller.modelChanged(this.buttonModel);
			}else{
					this.buttonModel.disabled = true;
					this.controller.modelChanged(this.buttonModel);
			}
	},
	
	passwordChanged: function (event) {
		this.toggleDisabled();
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode))
		{
			if (this.acctPasswordModel.original.length == 0)
			{
				this.controller.get("newPassword").mojo.focus.delay(0);
			}
			else
				this.controller.get("confirmPassword").mojo.focus.delay(0);
		}
	},
	
	verifyPasswordChanged: function (event) {
		this.toggleDisabled();
		if (event && Mojo.Char.isEnterKey(event.originalEvent.keyCode))
		{
			if (this.verifyPasswordModel.verify.length == 0)
			{
				this.controller.get("confirmPassword").mojo.focus.delay(0);
			}
			
			if (this.buttonModel.disabled == false)
			{
				this.changePassword();
				Event.stop(event);
			}
		}
		
			
		
	},
	
	clearFields : function()
	{
		this.acctPasswordModel.original = '';
		this.verifyPasswordModel.verify = '';
		this.controller.modelChanged(this.acctPasswordModel);
		this.controller.modelChanged(this.verifyPasswordModel);
	},
	
	clearErrorMessages: function() {
		this.controller.get("mismatchMessage").hide();
		this.controller.get("noPasswordMessage").hide();
		this.controller.get("noConfirmMessage").hide();
		this.controller.get("systemErrorMessage").hide();
		this.controller.get("passwordLengthError").hide();
	},
	
	changePassword: function() {
		this.newPassword = this.acctPasswordModel.original;
		this.confirmPassword = this.verifyPasswordModel.verify;
		this.clearErrorMessages();
		if(this.newPassword == "" || this.newPassword == undefined) {
			this.controller.get("noPasswordMessage").show();
			return;
		}
		else if ((this.newPassword.length < ProfileUtil.MINPASSWORDLENGTH) 
			|| (this.confirmPassword.length < ProfileUtil.MINPASSWORDLENGTH)
			|| (this.newPassword.length > ProfileUtil.MAXPASSWORDLENGTH)
			|| (this.confirmPassword.length > ProfileUtil.MAXPASSWORDLENGTH)) {
			this.controller.get("passwordLengthError").show();
			
				this.toggleDisabled();
				this.clearFields();
				this.controller.get('newPassword').mojo.focus.delay(0);
			
			return;
		}
		else if (this.confirmPassword == "" || this.confirmPassword == undefined) {
			this.controller.get("noConfirmMessage").show();
			return;
		} 
		else if (this.newPassword != this.confirmPassword) {
			this.controller.get("mismatchMessage").show();
			this.toggleDisabled();
			this.controller.get('newPassword').mojo.focus.delay(0);
			return;
		} 
			
		if (isConnectionAvailable === false) //why type+value compare
		{
			Mojo.Log.info("show connection error -------");
			ProfileUtil.showConnectionError(this.controller);
			return;
		}
		
		this.buttonModel.disabled = true;
		this.controller.modelChanged(this.buttonModel);
		
		AppAssistant.accountService.changePassword(
						this.newPassword, 
						this.myProfile.questionId, "", this.myProfile.idToken,
						true,
						this.changePasswordSuccess.bind(this), 
						this.changePasswordError.bind(this), 
						this.controller);
	},
	
	changePasswordSuccess: function (response) {
		Mojo.Log.info("ChangePassword successful :%o", $H(response));
		if (response.returnValue == true)
		{
			this.myProfile.password = this.newPassword;
			this.sceneAssistant.acctPassword = this.newPassword;
			this.widget.mojo.close();
			var bannerParams = {
        		icon: "images/tap-info.png",
        		messageText: this.usrpwd_confirm_message
   			};
			this.controller.showBanner(bannerParams, {}, 'pubsubbanner'); 
			
			this.getCredentials(); //move on to profile log-in
		}
	},
	
	changePasswordError: function(response){
		Mojo.Log.error("changePassword error = %o", $H(response));
		if ((isConnectionAvailable === false) || (reponse.errorText && response.errorText === "No response")) {
			Mojo.Log.info("show conncetion error ----------");
			this.widget.mojo.close();
			ProfileUtil.showConnectionError(this.controller);
			return;
		}
		
		this.controller.get("systemErrorMessage").show();
	},
	
	getCredentials: function() {
	    if (isConnectionAvailable === false) {
	    	ProfileUtil.showConnectionError(this.controller);
	    	return;
	    }
	
	    this.getAccountToken();
	},
  
	getAccountToken: function() {
		Mojo.Log.info("------------------- Get account token ------------------");
    	AppAssistant.accountService.getAccountToken(this.readAccountToken.bind(this),
            this.accountTokenError.bind(this), this.controller);
	},
	
	readAccountToken: function (response) {
	    if (response.accountAlias != undefined) { //The trunk refers to the unnamed branch (version) of a file tree under revision control. The trunk is usually meant to be the base of a project on which development progresses. If developers are working exclusively on the trunk, it always contains the latest cutting-edge version of the project, but therefore may also be the most unstable version. Another approach is to split a branch off the trunk, implement changes in that branch and merge the changes back into the trunk when the branch has proven to be stable and working. Depending on development mode and commit policy the trunk may contain the most stable or the least stable or something-in-between version.
		      this.myProfile.email = response.accountAlias;
		      this.myProfile.state = response.accountState;
		      this.myProfile.token = response.token;
			
			  if(this.myProfile.isTokenNeeded === true) {
			  	this.authenticateRequest = AppAssistant.accountService.authenticateAccount(
																				this.myProfile.email, this.myProfile.password,
																				this.authenticateSuccess.bind(this),
																				this.authenticateError.bind(this), this.controller
				);
			  }		
		      this.deviceIdRequest = AppAssistant.accountService.getDeviceId(
		                    this.readDeviceId.bind(this),
		                    this.errorDeviceId.bind(this),
		                    this.controller);
	    } else {
	      //TODO Handle missing account token case
	    }
	},
	
	authenticateSuccess: function (response) {
		Mojo.Log.info("--------------- Authentication successful -----------------%j", response);
	},
	
	authenticateError: function (response) {
		Mojo.Log.error("--------------- Authentication error -----------------%j", response);
	},
	
	readDeviceId: function (response) {
    	Mojo.Log.info("Read device id %o", $H(response));
		if (response && response.deviceId) {
		AppAssistant.accountService.isUserValid(
			this.myProfile.email, this.myProfile.password, response.deviceId,
			this.checkIfUserValid.bind(this), this.invalidUser.bind(this), this.controller);
		}
	    else
	 	{
	      //errorcase 
		}
	},
  
	accountTokenError: function(response) {
    	Mojo.Log.info("No account token = %o", $H(response));
	},
	
	errorDeviceId: function (response) {
		Mojo.Log.error("Could not get device id %o", $H(response));
	},

	checkIfUserValid: function (response) {
		Mojo.Log.info("Logging in after changing password");
		
		
		if(response.isValid === true) {
			//This is the temp token used for preferences
			this.myProfile.idToken = response.idToken;
			Mojo.Controller.stageController.swapScene("account", this.myProfile);
		} else {
			Mojo.Log.error("Could not log in after password change");
			//CASE NOT HANDLED YET!!
			//by default the program goes back to backup view
		}	
	}, 
	
	invalidUser: function(response) {
		Mojo.Log.info("Login error: "+$H(response).inspect());
		if(response.errorCode && response.errorCode === "CONNECTION_ERROR") {
			this.widget.mojo.close();
			ProfileUtil.showConnectionError(this.controller);
		}
	}
})




