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

function DashboardMessageAssistant(dashboardData) {
	this.dashboardData = dashboardData; // hold onto a reference to the dashboardData
	this.appController = Mojo.Controller.getAppController();
	this.Messaging = this.appController.Messaging;
	this.tapHandler = this.tapHandler.bindAsEventListener(this);
	this.oldPresenceClass = "";
}

DashboardMessageAssistant.prototype.setup = function() {
	this.update(true);
	this.messageInfoElement = this.controller.get('message_info');
	this.messageInfoElement.addEventListener(Mojo.Event.tap, this.tapHandler);
};

DashboardMessageAssistant.prototype.cleanup = function() {
	// If the dashboard is unloaded then wipe out our data
	this.appController.notificationAssistant.resetNewMessages();
	this.messageInfoElement.removeEventListener(Mojo.Event.tap, this.tapHandler);
};

DashboardMessageAssistant.prototype.update = function(isNewContent) {
	// TODO close the dashboard if dashboardData is empty?
	if (!this.dashboardData || this.dashboardData.newest == undefined) {
		Mojo.Log.error("DashboardMessageAssistant.update called with empty data.");
		Mojo.Log.error("%j", this.dashboardData);
		this.closeDashboard();
		return;
	}
	
	var data = this.dashboardData[this.dashboardData.newest].list;
	var numConversations = Object.keys(this.dashboardData).length - 1; // subtract one because of the 'newest' property

	var dModel = {
		conversationCount: numConversations,
		singleMessageClass: "single",
		unreadMessageCount: data.length,
		topLine: "",
		bottomLine: "",
		rightImage: "",
		messageId: "",
		rightImageClass: "hidden", // setting this to something other than hidden will make it visible
		displayAttachment: "style='display:none;'"
	}
  
	if (numConversations > 1) {
		dModel.singleMessageClass = "multi";
	}

	for (var i = 0; i < data.length; i++) {
		if (data[i].messageType == "MMS") {
			dModel.displayAttachment = "";
			break;
		}
	}

	var conversationText = data.last().message;
	dModel.topLine = data[0].name;
	// TODO: this was added as a temporary patch to display number of messages from a given person.
	if (data.length > 1) {
		dModel.topLine = dModel.topLine + " (" + data.length + ")";
	}
	dModel.bottomLine = conversationText;	

	var renderedInfo = Mojo.View.render({object: dModel, template: 'dashboardMessage/message-info'});

	// Insert the HTML into the DOM, replacing the existing content.
	Element.update(this.controller.get('message_info'),renderedInfo);

	MessagingMojoService.reverseLookup(this.controller, data[0].address, this.handleContactDetails.bind(this), this.removePresence.bind(this));
	
	if(isNewContent) {
		this.controller.stageController.indicateNewContent(true);
	}
};

DashboardMessageAssistant.prototype.removePresence = function(response) {
	Mojo.Log.info("DashboardMessageAssistant.removePresence %j", response);
	if (this.presenceSubscription !== undefined) {
		this.controller.cancelServiceRequest(this.presenceSubscription);
	}
	this.presenceSubscription = undefined;

	var presenceIcon = this.controller.get('presence-icon');
	if (presenceIcon !== undefined) {
		presenceIcon.removeClassName(this.oldPresenceClass);
	}
	this.oldPresenceClass = "";
};

DashboardMessageAssistant.prototype.handleContactDetails = function(response) {
	if (this.presenceSubscription !== undefined) {
		this.controller.cancelServiceRequest(this.presenceSubscription);
	}
	this.presenceSubscription = undefined;

 	if (response.match && response.match.type == "IM") {
		this.presenceSubscription = MessagingMojoService.observeIMAddress(this.controller, response.match.value, response.match.serviceName, this.handlePresenceChanges.bind(this));
	}
	
	//Display avatar 
	if (response.record && response.record.pictureLocSquare) {
		Mojo.Log.info("Displaying sender's picture %s", response.record.pictureLocSquare);
		var imgElem = this.controller.get('avatar');
		imgElem.src = "file://" + response.record.pictureLocSquare;
		this.controller.get('avatar-container').show();
	} else {
		this.controller.get('avatar-container').hide();
	}
};

DashboardMessageAssistant.prototype.handlePresenceChanges = function(response) {
	var presenceIcon = this.controller.get('presence-icon');
	if (presenceIcon !== undefined) {
		var className = this.Messaging.Availability.getPopupAvailabilityClass(response.record.availability);
		Mojo.Log.info("Dashboard presence: new class %s, old class %s", className, this.oldPresenceClass);
		if (className != this.oldPresenceClass) {
			presenceIcon.removeClassName(this.oldPresenceClass);
			presenceIcon.addClassName(className);
			this.oldPresenceClass = className;
		}
	}
};

DashboardMessageAssistant.prototype.tapHandler = function(event) {
	var data = this.dashboardData[this.dashboardData.newest].list;
	// if we only have one message, launch to that chat
	if(data.length == 1) {
		MessagingMojoService.launchMessaging(this.controller,{"chatThreadId":data[0].chatThreadId});
	} else {
		var target = event.target;
		// Clicked on the message count -> launch to conversation history view
		MessagingUtils.simpleListClick(target,"palm-dashboard-icon-container",function(newTarget){
			MessagingMojoService.launchMessaging(this.controller,{launchListView: true, forceListView:this.Messaging.Views.HISTORY});
		}.bind(this));
	
		// Clicked on the last message -> launch the chatview
		MessagingUtils.simpleListClick(target,"palm-dashboard-text-container",function(lastMessage,newTarget){
			MessagingMojoService.launchMessaging(this.controller,{"chatThreadId":lastMessage.chatThreadId});
		}.bind(this,data[0]));
	}
};

DashboardMessageAssistant.prototype.closeDashboard = function(){
	this.controller.window.close(); 
};