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

var PrefsConstants = {
	lastFirst: 'LAST_FIRST',
	firstLast: 'FIRST_LAST',
	companyLastFirst: 'COMPANY_LAST_FIRST',
	companyFirstLast: 'COMPANY_FIRST_LAST',
};

var PrefsAssistant = Class.create({
    initialize: function() {
   		this.defaultAccountsList = [];
    },
		
	setup: function() {
		this.accountsList = this.controller.get("AccountsList");
    	this.openDefaultPickerBound = this.openDefaultPicker.bind(this);
		this.defaultAccountItem = this.controller.get('defaultAccount');
		this.defaultAccountItem.observe(Mojo.Event.tap, this.openDefaultPickerBound);
		
		this.accountsAttributes = {
			itemTemplate : "prefs/existingAccount",
			listTemplate: 'common/group_container'
		};
		this.accountsModel = {
			items : [],
			listTitle: $L({value: "Accounts", key: "accounts_list_title"})
		};
		this.controller.setupWidget("AccountsList", this.accountsAttributes, this.accountsModel);
		this.newAccountButton =  this.controller.get('NewAccountButton')
		this.newAccountAction = function() {
			this.controller.stageController.pushScene("choosetransport", "prefs", null, $L("Contacts accounts"), $L("Done"));
		}.bind(this);
		this.newAccountButton.observe(Mojo.Event.tap, this.newAccountAction);
		this.handleAccountsListTapBound = this.handleAccountsListTap.bind(this);
		this.accountsList.observe(Mojo.Event.listTap, this.handleAccountsListTapBound);
		
		
		this.controller.setupWidget('SortSelector', {choices: this.sorts, modelProperty: 'sortOrder'}, this);
		this.sortSelector = this.controller.get('SortSelector');
		this.sortChangedBound = this.sortChanged.bindAsEventListener(this);
		this.sortSelector.observe(Mojo.Event.propertyChange, this.sortChangedBound);
		
		AppAssistant.contactsService.getSortOrder(this.controller, this.handleSortOrder.bind(this));
		this.renderAccountsListBound = this.renderAccountsList.bind(this);
		AppAssistant.accountsService.getAllAccountsForService(this.controller, AccountsService.CONTACTS, true, this.renderAccountsListBound);
		AppAssistant.contactsService.getDefaultAccount(this.handleDefaultAccount.bind(this), this.controller);
		
		this.controller.setupWidget("SyncAccountsButton", {}, {buttonLabel: $L("Sync Now")});
		this.syncAccountsBound = this.syncAccounts.bind(this);
		this.controller.listen("SyncAccountsButton", Mojo.Event.tap, this.syncAccountsBound);
	},
	
	aboutToActivate: function(callback) {
		this.aboutToActivateCallback = callback;
	},
	
	activate: function() {
		// dont manually insert if we didn't beat the clock.
		if (this.aboutToActivateCallback) {
			delete this.aboutToActivateCallback;
		}
	},
	
	cleanup: function() {
		this.defaultAccountItem.stopObserving(Mojo.Event.tap, this.openDefaultPickerBound);
		this.newAccountButton.stopObserving(Mojo.Event.tap, this.newAccountAction);
		this.sortSelector.stopObserving(Mojo.Event.propertyChange, this.sortChangedBound);
		this.accountsList.stopObserving(Mojo.Event.listTap, this.handleAccountsListTapBound);
		this.controller.stopListening("SyncAccountsButton", Mojo.Event.tap, this.syncAccountsBound);
	},
	
	sorts: [
		{ label: $L('First name'), value: PrefsConstants.firstLast },
		{ label: $L('Last name'), value: PrefsConstants.lastFirst },
		{ label: $L('Company & first name'), value: PrefsConstants.companyFirstLast },
		{ label: $L('Company & last name'), value: PrefsConstants.companyLastFirst }
	],
	
	handleDefaultAccount: function(response) {
		this.defaultAccountId = response.defaultAccountId;
		
		if (this.accountsModel.items && this.accountsModel.items.length > 0) {
			this.updateDefaultAccountPicker();
		}
		this.defaultAccountReturned = true;
		this.tryToActivate();
	},
	
	updateDefaultAccountPicker: function() {
		var that = this;
		var acct = this.accountsModel.items.find(function(a){
			return a.accountId == that.defaultAccountId;
		});
		
		if (!acct) {
			Mojo.Log.warn("unable to find default account id=", this.defaultAccountId);
		}
		
		this.controller.get('defaultAccount').update(Mojo.View.render({
			template: 'prefs/defaultAccount',
			object: acct
		}));
	},
	
	renderAccountsList: function(resp) {
		this.easAccounts = $A(); //TODO: make this a normal array?
		var that = this;
		resp.list.each(function(item) {
			item.label = item.login || item.accountDisplayName || "BAD ACCOUNT: " + item.accountId;
			item.loginDisplayName = item.originalLogin || item.login;
			
			//for AAB accounts, we strip the @att.com part
			if (item.domain === "att" && item.loginDisplayName.endsWith("@att.com")) {
				item.loginDisplayName = item.loginDisplayName.substr(0, item.loginDisplayName.lastIndexOf("@att.com"));
			}
			
			item.iconPath = Utilities.iconJSONToIconPath(item.accountSpecificIcons);
			item.command = item.accountId;
			item.accountHidden = item.accountHidden * 1;  // turn it into a number for evaluation
			if (item.domain === "eas") {
				that.easAccounts.push(item.accountId);
			}
			item.accountDisplayName = $L(item.accountDisplayName);
		});
		this.accountsModel.items = resp.list;
		this.defaultAccountsList.clear();
		var that = this;
        resp.list.each(function(acct) {
            if (acct.accountDataIsReadOnly == "0" && acct.domain !== "simphonebook") {
				var name = acct.accountDisplayName;
				if (acct.login) {
					name = name + " (" + acct.login + ")";
				}
				var path = Utilities.iconJSONToIconPath(acct.accountSpecificIcons);
                that.defaultAccountsList.push({
                    label: name,
                    secondaryIconPath: path,
                    command: acct.accountId
                });
            }
        })
		this.controller.modelChanged(this.accountsModel);
		
		if (this.defaultAccountId) {
			this.updateDefaultAccountPicker();
		}
		
		this.accountsListReturned = true;
		this.tryToActivate();
	},
	
	tryToActivate: function() {
		if (this.aboutToActivateCallback && this.accountsListReturned && this.defaultAccountReturned && this.sortOrderReturned) {
			this.aboutToActivateCallback.defer();
			delete this.aboutToActivateCallback;
		}
	},
	
	handleAccountsListTap: function(event) {
		if (event.item.accountHidden || event.item.isCrudAccount == "1") {
			//Lets just show the contact count as a popup
			AppAssistant.contactsService.countAccountsContacts(this.controller, event.item.accountId, this.popupNumberOfContacts.bind(this, event.item.accountDisplayName));
			//Mojo.Log.info("Ignoring accounts list tap; account tag=", event.item.accountTag, "is marked 'hidden'");
		} else if (event.item.domain === "att") {
			var loginParams = {
				acctId: event.item.accountId,
				acctLogin: event.item.login,
				acctTypeId: 0,
				acctDomain: event.item.domain,
				acctName: event.item.name,
				iconClass: event.item.iconClass,
				numberOfTimesToPopScene: 1
			};
			this.controller.stageController.pushScene({
				appId: "com.palm.app.attsyncpanel",
				name: "accountlogin"
			}, loginParams);
		} else {
			var loginParams = {
				acctId: event.item.accountId,
				acctLogin: event.item.login,
				acctTypeId: 0,
				acctDomain: event.item.domain,
				acctName: event.item.name,
				iconClass: event.item.iconClass,
				numberOfTimesToPopScene: 1
			};
			this.controller.stageController.pushScene("accountlogin", loginParams);
		}
	},
	
	popupNumberOfContacts: function(name, resp) {
		var template = $L("#{count} Contacts");
		var numPeople = resp.contactCount;
		if (numPeople == 1) {
			template = $L("1 Contact");
		}
		var message = template.interpolate({ count: numPeople });
		this.controller.showAlertDialog({
			message: message,
			title: name,
			choices: [{ label: $L("OK") }]
		});
	},
	
	handleSortOrder: function(response) {
		this.sortOrder = response.order;
		this.controller.modelChanged(this);
		this.sortOrderReturned = true;
		this.tryToActivate();
	},
	
	sortChanged: function(e) {
		AppAssistant.contactsService.setSortOrder(this.controller, this.sortOrder, function() {
			if (AppAssistant.listResetCallback) {
				AppAssistant.listResetCallback();
			}
		});
	},
	
	openDefaultPicker: function(e) {
		this.controller.popupSubmenu({
	        onChoose: this.handlePrimaryChange.bind(this),
	        toggleCmd: this.defaultAccountId, 
	        placeNear: e.target,
	        items: this.defaultAccountsList			
		});
	},
	
	handlePrimaryChange: function(accountId) {
		if (!accountId) {
			return;
		}
		
		Mojo.Log.info("Contacts: setting default to id: ", accountId);
		AppAssistant.contactsService.setDefaultAccount(this.controller,accountId);
		AppAssistant.defaultAccountId = accountId;
		this.handleDefaultAccount({ defaultAccountId: accountId });
	},
	
	syncAccounts: function() {
		AppAssistant.pimSyncService.syncAll(this.controller, this.easAccounts, this.showSyncing.bind(this));
	},
	
	showSyncing: function() {
		this.controller.showBanner($L("Syncing Accounts..."), {});
	}
	
});
