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

*/

var EmailDashboardAssistant = Class.create({
	
	initialize: function(notificationAssistant, notifications) {
		this.notificationAssistant = notificationAssistant;
		this.notifications = notifications;
		this.allInboxesOn = this.notificationAssistant.allInboxesOn;
	},

	setup: function() {
		this.update(this.notifications);
		this.boundTapHandler = this.tapHandler.bindAsEventListener(this);
		this.controller.sceneElement.observe(Mojo.Event.tap, this.boundTapHandler);
	},

	cleanup: function() {
		if (!this.ignoreClear) {			
			if (this.allInboxesOn) {
				// when the dashboard is dismissed, we should reset the new email count.
				// we can do this by clearing all the new email notifications from mail
				// transport by providing folderId of -1 and the current timestamp.  
				this.notificationAssistant.setFolderViewedTimestamp(-1, new Date().getTime());
				this.notificationAssistant.resetNotifications();
			}
			else {
				var folderId = this.notifications[0].folder;
				var accountId = this.notifications[0].account;
				var stageName = NotificationAssistant.kNewEmailDashboardStageName + accountId;
				
				this.notificationAssistant.setFolderViewedTimestamp(folderId, new Date().getTime());
				this.notificationAssistant.clearAccount(accountId);
			}
		}
		
		this.controller.sceneElement.stopObserving(Mojo.Event.tap, this.boundTapHandler);
		// turn off throbber
		Mojo.Log.info('Turning off throbber');
		this.controller.stageController.indicateNewContent(false);
	},

	tapHandler: function(event) {
		// Ignore additional taps in case the user is impatient
		var target = event.target;
		if (!target.hasClassName('email-dashboard-tap-target')) {
			target = target.up('div.email-dashboard-tap-target');
		}

		event.stopPropagation();
		if (target) {
			// disable the tap event to prevent keep handling user's multiple taps
			if (!this.allInboxesOn) 
				this.controller.sceneElement.stopObserving(Mojo.Event.tap, this.boundTapHandler);
			
			var accountId = target.readAttribute('accountid');
			Mojo.Log.info("EmailDashboardAssistant.tapHandler found target accountid="+accountId);
			if (accountId == "single") {
				var folderId = target.readAttribute('folderid');
				var messageId = target.readAttribute('messageid');
				this.showSingleMessage(accountId, folderId, messageId);
			} else if (accountId == "all") {
				this.showAccount(); // just display the account scene
			} else {
				this.showAccount(accountId);
			}
		}
	},

	update: function(notificationInfo) {
		if (!this.notificationAssistant) {
			Mojo.Log.error("I feel a disturbance in the Force... As if notificationAssistant isn't there");
			return;
		}

		var content;
		var latestDetails;

		// turn on throbber
		Mojo.Log.info('Turning on throbber for new email notification');
		this.controller.stageController.indicateNewContent(true);
		
		// update notifications if they are changed.
		this.notifications = notificationInfo;
		 
		if (notificationInfo.length === 1) {
			latestDetails = this.getEscapedNotification(notificationInfo[0]);

			if (latestDetails.count === 1) {
				latestDetails.accountDomain = FolderFlags.getFolderHeaderIcon(latestDetails.accountDomain);
				content = Mojo.View.render({
					object: latestDetails,
					template: 'email-dashboard/single-email-template'
				});
			} else {
				latestDetails.accountDomain = FolderFlags.getFolderHeaderIcon(latestDetails.accountDomain);
				content = Mojo.View.render({object: latestDetails, template: 'email-dashboard/single-account-template'});
			}
		} else {
			var count = 0;
			var latestTimestamp = 0;
			var folderObj;
			var listIndex;
			for (listIndex = 0; listIndex < notificationInfo.length; ++listIndex) {
				folderObj = notificationInfo[listIndex];
				count += folderObj.count;
				if (folderObj.timestamp > latestTimestamp) {
					latestTimestamp = folderObj.timestamp;
					latestDetails = folderObj;
				}
			}

			latestDetails = this.getEscapedNotification(latestDetails);
			var obj = {
				total: count,
				folder: latestDetails.folder,
				message: latestDetails.message,
				from: latestDetails.from,
				summary: latestDetails.summary
			};
			content = Mojo.View.render({object: obj, template: 'email-dashboard/multiple-accounts-template'});
		}
	
		this.controller.sceneElement.update(content);
	},
	
	getEscapedNotification: function(folderObj) {
		// Cloning 'folderObj' is to avoid the original 'from' and 'summary' fields
		// to be escaped multiple times during updates.  We want to retain their
		// original values. 
		// 'folderObj' contains primitives, it is okay to create a shallow copy of it.
		var obj = Object.clone(folderObj);
		
		// escape any html tags in the subject so they display as markup text rather than
		// rendering as html.
		if (obj.from) {
			obj.from = obj.from.escapeHTML();
		}

		if (obj.summary) {
			obj.summary = obj.summary.escapeHTML();
		} else {
			obj.summary = Message.kNoSubjectString;
		}
		
		return obj;
	},

	showSingleMessage: function(account, folder, message) {
		this.notificationAssistant.setFolderViewedTimestamp(folder, new Date().getTime());
		this.notificationAssistant.clearAccount(account, folder, message);
		this.ignoreClear = true;
				
		var folderInfo = { folderId: folder,
		                   accountId: account,
//		                   login: latestNotification.login,
//		                   domain: latestNotification.accountDomain
			             };
	    // Mojo.Log.info("**** email-dashboard-assistant -- sending showSingleMessage request");
		this.controller.serviceRequest('palm://com.palm.applicationManager', {
	                    method: 'open',
	                    parameters: {
							id: 'com.palm.app.email',
							params: { 'debounce': 'm'+message,
							          'emailId': message,
							          'folderInfo': folderInfo}
						}
	                });
	},

	showFolder: function(accountId, folderId, resp) {
		this.notificationAssistant.setFolderViewedTimestamp(folderId, new Date().getTime());
		this.notificationAssistant.clearAccount(accountId, folderId);
		this.ignoreClear = true;
		
		var folderInfo = { folderId: folderId,
		                   accountId: accountId,
		                   login: resp.address,
		                   domain: resp.accountDomain
			             };
		//Mojo.Log.info("email: showFolder accountId=", accountId, ", folderId=", folderId, ", resp=", $H(resp).inspect());
		this.controller.serviceRequest('palm://com.palm.applicationManager', {
	                    method: 'open',
	                    parameters: {
							id: 'com.palm.app.email',
							params: { 'debounce': 'f'+folderId, 'folderInfo': folderInfo }
						}
	                });
	},

	showAccount: function(accountId) {
		var folderList = this.notificationAssistant.getFoldersList(accountId);
		
		//If there's only one folder, open into that folder
		if (folderList.length == 1) {
			var folderId = folderList[0] +"";
			EmailAccount.getAccountDetails(this.controller, accountId, this.showFolder.bind(this, accountId, folderId));
		} else {
			this.notificationAssistant.setFolderViewedTimestamp(-1, new Date().getTime());
			this.notificationAssistant.clearAccount(accountId);
			this.ignoreClear = true;
		
			// Just open to the accounts scene
			this.controller.serviceRequest('palm://com.palm.applicationManager', {
		                    method: 'open',
		                    parameters: {
								id: 'com.palm.app.email',
								params: { 'debounce': 'accounts' }
							}
		                });
		}
	},
	
	setCleanupParams: function(params) {
		this.ignoreClear = params.ignoreClear;
		this.allInboxesOn = params.allInboxesOn;
	},

});
