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

Photos.Scene.Accountlogin = Class.create(Photos.Scene.Base, {
	setup: function($super) {
		$super();
		this.deleteButtonModel = {
			buttonLabel: $L('Remove account'),
			buttonClass: 'negative'
		};
		this.addButton = this.controller.get('add_button');
		this.deleteButton = this.controller.get('delete_button');
		this.controller.get('account_icon').addClassName(
					this.sceneModel.getService().domain);

		if (this.sceneModel.getPasswordOnly()) {
			this.userFieldModel = {
				disabled: true,
				text: this.sceneModel.getService().displayLogin
			};
			this.deleteButton.style.display = "block";
			this.controller.get('header_span').update(
					$L("Change login settings"));
			this.addButtonModel =
					{buttonLabel: $L("Change password")};
		} else {
			this.userFieldModel = {};
			this.deleteButton.style.display = "none";
			this.controller.get('header_span').update(
							$L("Add an account"));
			this.addButtonModel = {buttonLabel: $L("Sign in")};
		}

		this.passFieldModel = {disabled: false};

		this.controller.setupWidget('user_field', {
			focus: !this.sceneModel.getPasswordOnly(),
			textReplacement: false,
			modelProperty: "text"
		}, this.userFieldModel);
		this.controller.setupWidget('pass_field',
				{focus: this.sceneModel.getPasswordOnly()},
				this.passFieldModel);

		this.controller.setupWidget('add_button',
					{type: Mojo.Widget.activityButton},
					this.addButtonModel);
		this.controller.setupWidget(
			'delete_button', {}, this.deleteButtonModel);

		this.autoListen(this.addButton, Mojo.Event.tap,
			this.handleAdd.bind(this));
		this.autoListen(this.deleteButton, Mojo.Event.tap,
			this.handleDelete.bind(this));

		this.disablePrefsMenu();
	},

	handleDelete: function() {
		this.enableUI(false);
		this.controller.serviceRequest('palm://com.palm.accounts', {
			method: 'removeService',
			parameters: {
				accountId: this.sceneModel.getService().accountId,
				service: "PHOTO_UPLOAD"
			},
			onSuccess: this.deleteOkay.bind(this),
			onFailure: this.deleteFail.bind(this)
		});
	},

	handleAdd: function() {
		this.enableUI(false);

		if (this.sceneModel.getPasswordOnly()) {
			if (!this.controller.get('pass_field').mojo.getValue()) {
				this.controller.stageController.popScenesTo('accounts');
				return;
			}

			this.controller.serviceRequest(
			'palm://com.palm.photos', {
				method: 'updateAccountCredentials',
				parameters: {
					accountId: this.sceneModel.getService().accountId,
					username: this.sceneModel.getService().login,
					password: this.controller.get('pass_field').mojo.getValue()
				},
				onSuccess: this.passUpdateOkay.bind(this),
				onFailure: this.passUpdateFail.bind(this)
			});

			Mojo.Log.info("Trying to update account:",
				this.sceneModel.getService().accountId,
				Object.toJSON(this.sceneModel.getService()));
		} else {
			this.controller.serviceRequest(
			'palm://com.palm.photos', {
				method: 'login',
				parameters: {
					setupRelated: true,
					accountTypeId: this.sceneModel.getService().id,
					username: this.controller.get('user_field').mojo.getValue(),
					password: this.controller.get('pass_field').mojo.getValue()
				},
				onSuccess: this.loginOkay.bind(this),
				onFailure: this.loginFail.bind(this)
			});

			Mojo.Log.info("Trying to add account:",
				this.sceneModel.getService().id,
				Object.toJSON(this.sceneModel.getService()));
		}
	},

	enableUI: function(enabled) {
		if (this.uiEnabled == enabled) {
			return;
		}

		if (!this.sceneModel.getPasswordOnly()) {
			if (enabled) {
				this.addButtonModel.buttonLabel = $L("Sign in");
				this.controller.get('add_button').mojo.deactivate();
			} else {
				this.addButtonModel.buttonLabel = $L("Signing in...");
				this.controller.get('add_button').mojo.activate();
			}
		}

		this.uiEnabled = enabled;
		this.deleteButtonModel.disabled = !enabled;
		this.addButtonModel.disabled = !enabled;
		this.userFieldModel.disabled = !enabled;
		this.passFieldModel.disabled = !enabled;

		if (!this.sceneModel.getPasswordOnly()) {
			this.userFieldModel.disabled = !enabled;
			this.controller.modelChanged(this.userFieldModel);
		}
		this.controller.modelChanged(this.passFieldModel);
		this.controller.modelChanged(this.deleteButtonModel);
		this.controller.modelChanged(this.addButtonModel);
	},

	loginOkay: function(response) {
		Mojo.Log.info("Login okay", Object.toJSON(response));
		this.controller.stageController.popScenesTo('accounts');
	},

	loginFail: function(response) {
		Mojo.Log.info("Failed to login", Object.toJSON(response));
		var errorMsg = $L('Login failed.');
		this.showError(errorMsg, response);
		this.enableUI(true);
	},

	deleteOkay: function(response) {
		Mojo.Log.info("Delete Okay.", Object.toJSON(response));
		this.controller.stageController.popScenesTo('accounts');
	},

	deleteFail: function(response) {
		Mojo.Log.info("Failed to remove account",
						Object.toJSON(response));
		this.showError($L("Failed to remove account"), response);
		this.enableUI(true);
	},

	passUpdateOkay: function(response) {
		Mojo.Log.info("Password change Okay", Object.toJSON(response));
		this.controller.stageController.popScenesTo('accounts');
	},

	passUpdateFail: function(response) {
		Mojo.Log.info("Failed to change password:",
						Object.toJSON(response));
		this.showError($L("Failed to change password."), response);
		this.enableUI(true);
	},

	showError: function(message, response) {
		var errorMsg;
		var t = this.controller.prepareTransition(
						Mojo.Transition.crossFade);
		var msgStrs = {
		"AcctMgr_Network_Error" :
			$L("Could not connect to the server. Try again."),
		"AcctMgr_Bad_Username":
			$L("Username is incorrect. Try again."),
		"AcctMgr_Bad_Password":
			$L("Password is incorrect. Try again."),
		"AcctMgr_Bad_Authentication":
			$L("The username or password is incorrect. Try again."),
		"AcctMgr_Generic_Error":
			$L("Sign in failed. Try again."),
		"AcctMgr_Account_Locked":
			$L("Account locked."),
		"AcctMgr_Acct_Already_Exists":
			$L("Account already exists."),
		"AcctMgr_Acct_Not_Created": $L("Account not created."),
		"AcctMgr_No_Setup_Service": $L("No setup service.")    
	   	};
		
		this.controller.get('error_container').style.display = "block";
		if(response.errorMessage && msgStrs[response.errorMessage]) {
			errorMsg = msgStrs[response.errorMessage];
		} else {
			errorMsg = message;
		}
		this.controller.get('error_content').innerHTML = errorMsg;
		t.run();
	},

	hideError: function() {
		var t = this.controller.prepareTransition(
						Mojo.Transition.crossFade);
		this.controller.get('error_container').style.display = "none";
		this.controller.get('error_content').innerHTML = "";
		t.run();
	}
});

