/* Copyright 2009-2010 Palm, Inc.  All rights reserved. */
/*global Mojo, Class, $L, FirstUseUtil, AppAssistant */
/*jslint rhino:true, undef:true */

var AccountsLoginAssistant = Class.create({
	
	initialize: function(userAccounts) {
		this.userAccounts = userAccounts;
		this.accountsList = [];
		this.loggedInAccountSize = 0;
		FirstUseUtil.addDashboardSmall($('target'));
		saveCurrentState("accounts-login");
	},

	setup: function() {
		this.buttonAttr = {
			disabledProperty: 'disabled'
		};
		this.buttonModel = {
			buttonLabel : $L('Skip'),
			buttonClass: 'palm-button'
		};
		this.controller.setupWidget('button_skip', this.buttonAttr, this.buttonModel);
		Mojo.listen(this.controller.get('button_skip'), Mojo.Event.tap, this.showRestoreComplete.bindAsEventListener(this));
		
		this.accountsModel = {
				listTitle: $L('Accounts'),
				items: []
			};
		this.controller.setupWidget('accountList',
			{
				itemTemplate: 'accounts-login/accounts-login-listitem',
				listTemplate: 'accounts-login/accounts-login-list'
			},
			this.accountsModel
		);
		
		// If accounts info has been passed from previous screen, use them. 
		if (this.userAccounts) {
			this.readAccounts(this.userAccounts);
		}
		// If user has come to this screen after a reboot, fetch accounts
		else {
			this.getAccounts();
		}	
		this.controller.listen('accountList', Mojo.Event.listTap, this.loginToAccount.bind(this));
		
		this.controller.listen(this.controller.get('target'), Mojo.Event.tap, FirstUseUtil.tapHandler.bindAsEventListener(this));
		
		// Listen to ## key presses
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
	},
	
	getAccounts: function () {
		this.accountsRequest = AppAssistant.accountsLoginService.listAccountsByCredentials(
					this.readAccounts.bind(this), this.errorAccounts.bind(this), this.controller);
	},
	
	readAccounts: function (response) {
		if(response.list) {
			var accounts = response.list;
			
			for (var i = 0; i < response.count; i++) {
				if(!(accounts[i].isVisted)) {
					var credId = accounts[i].credentialsId;
					
					this.isMatchFound = false;
					// Find if there are accounts with the same credentials id
					for (var j = i+1; j < response.count; j++) {
						// If yes, mark that as already visited. 
						//Only one account with the same credentials id will need to show up in the list
						if(credId === accounts[j].credentialsId) {
								accounts[j].isVisted = true;
								this.isMatchFound = true;
						}
					}
										
					this.account = accounts[i];
					
					// If original login is present, use it for display
					var email = this.account.originalLogin;
					var username = this.account.login;
					
					// Extract email address from originalLogin
					if(email) {
						var startIndex = email.indexOf("(");
						var endIndex = email.indexOf(")");
						if(startIndex > -1 && endIndex > -1) {
							username = email.slice(startIndex+1, endIndex);
						}
					} else {
						email = this.account.login;
					}
					
					var iconClass = this.account.iconClass;
					Mojo.Log.info("--------------- this.isMatchFound ---------------%j", this.isMatchFound);
					// If match is found, get the parent icon class to use
					if(this.isMatchFound === true) {
						iconClass = this.getIconClass(this.account.domain);
					} else {
						// Match is not found, use the icon class if available
						if((!iconClass) || (this.account.domain === "default")) {
							iconClass = this.getIconClass(this.account.domain);
						}
					}
					Mojo.Log.info("--------------- Pushing account ---------------%j", this.account);
					
					this.accountsList.push({
						'accountId': this.account.accountId,
						'credentialsId': this.account.credentialsId,
						'accountIconClass': iconClass,
						'checkmarkOrWarning': 'warning-small',
						'checked': '',
						'accountName': this.account.accountDisplayName,
						'username':username,
						'emailAddress': email
					});
					
				}	
			}
		} else {
			this.showRestoreComplete();
			return;
		}
		this.accountsModel.items = this.accountsList;
		this.controller.modelChanged(this.accountsModel);
	},
	
	getIconClass: function (domain) {
		// Get the icon class relevant to the domain 
		var iconClass = "default";
		switch (domain) {
			case 'gmail': 	iconClass = 'google';
						  	break;			  
			case 'yahoo': 	iconClass = 'yahoo';
						  	break;
			case 'eas':   	iconClass = 'eas';
						  	break;
			case 'facebook':iconClass = 'facebook';
						    break;
			case 'aol':		iconClass = 'aol';
						    break;
			case 'linkedin':iconClass = 'linked';
						  	break;
			default: 		iconClass = 'generic';
							break;			  
		}
		return iconClass;
	},
	
	errorAccounts: function (response) {
		Mojo.Log.error("-------Error in getting list of accounts to login ------------%j", response);
		this.showRestoreComplete();
	},
	
	showRestoreComplete: function () {
		Mojo.Controller.stageController.swapScene('restorecomplete');
	},
	
	loginToAccount: function (event) {
		if(event.item) {
			if (event.item.checked !== "checked") {
				var isLastAccount = false;
				if (this.loggedInAccountSize === this.accountsList.size() - 1) {
					isLastAccount = true;
				}
				Mojo.Log.info("------------------- isLastAccount -------------" + isLastAccount);
				Mojo.Controller.stageController.pushScene('accounts-login-password', event.item, isLastAccount);
			}	
		}
		
	},
	
	activate: function(account) {
		if(!account) {
			return;
		}
		// Change the button name from 'Skip' to 'Skip Remanining' if user has logged into atleast one account
		if (this.buttonModel.buttonLabel === "Skip") {
			this.buttonModel.buttonLabel = $L("Skip remaining");
			this.controller.modelChanged(this.buttonModel);
		}
		for (var i = 0; i < this.accountsList.size(); i++) {
			var id = this.accountsList[i].accountId;
			if (account.accountId === id) {
				this.accountsList[i].checkmarkOrWarning = 'checkmark';
				this.accountsList[i].checked = 'checked';
				this.controller.modelChanged(this.accountsModel);
				this.loggedInAccountSize = this.loggedInAccountSize+1;
				break;
			}	
		}
	}
	
});
