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

var Message = Class.create({ 
	initialize: function() { 
	}
});


Message.identifier = 'palm://com.palm.mail';

Message.kNoSubjectString = $L("No Subject");
Message.kNoSubjectText = "&lt;" + Message.kNoSubjectString + "&gt;";

Message.ATTACHMENT_LOAD_QUEUED_EVENT		= "0";
Message.ATTACHMENT_LOAD_STARTED_EVENT 		= "1";
Message.ATTACHMENT_LOAD_PROGRESS_EVENT 		= "2";
Message.ATTACHMENT_LOAD_COMPLETED_EVENT 	= "3";
Message.ATTACHMENT_LOAD_STOPPED_EVENT 		= "4";
Message.ATTACHMENT_LOAD_NOT_FOUND_EVENT 	= "5";


/**
 * Request account and folder details for a given message
 */
Message.getFolderAndAccount = function(controller, messageId, callback, error) {
	controller.serviceRequest(Message.identifier, {
		method: 'messageInfo',
		parameters: { 'message':messageId },
		onSuccess: callback,
		onFailure: function(err) { Mojo.Log.error("getFolderAndAccount",$H(err).inspect()); }
	});
}

Message.subscribeFolderMsgList = function(folderId, sortOrder, filter, offset, limit, callback, failCallback) {
	//console.log("Message.subscribeFolderMsgList " + folderId +" offset="+ offset +", limit="+ limit);
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'messageList',
			subscribe: true,
			parameters: {'folder':folderId, 'sortOrder':sortOrder, 'messagesFilter': filter, 'offset': offset, 'limit': limit, 'subscribe': true},
			onSuccess: callback,
			onFailure: failCallback
		});
	return request;
}

Message.getFolderMsgListLimit = function(params, callback) {
	//console.log("Message.getFolderMsgListLimit id " + folderId +", sub="+subscriberId +", offset="+offset +", limit="+limit);
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'messageList',
			parameters: params,
			onSuccess: callback
		});
	return request;
}

Message.getFolderMsgListCount = function(folderId, filter, callback) {
	//console.log("Message.getFolderMsgListCount id " + folderId);
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'messageCount',
			parameters: {'folder':folderId, 'messagesFilter': filter},
			onSuccess: callback,
			onFailure: function(r){Mojo.Log.error("count failure "+$H(r).inspect())}
		});
	return request;
}

/**
 * Return the full messsage data of an email message with the specified message id
 * @param {Object} messageId
 */
Message.getMessage = function(controller, messageId, callback, error) {
	controller.serviceRequest(Message.identifier, {
		method: 'messageDetail',
		parameters: { 'message':messageId },
		onSuccess: callback,
		onFailure: error
	});
}

Message.getMessageText = function(controller, messageId, callback, error) {
	controller.serviceRequest(Message.identifier, {
		method: 'messageFileText',
		parameters: { 'message':messageId },
		onSuccess: callback,
		onFailure: error
	});
}

Message.getNextMessage = function(controller, messageId, folderId, folderFilter, callback, error) {
	Mojo.Log.info("---------------> folderFilter: %s", folderFilter);
	controller.serviceRequest(Email.identifier, {
		method: 'getNextMessages',
		parameters: {'message':messageId, 'folder': folderId, 'folderFilter': folderFilter},
		onSuccess: callback,
		onFailure: error
	});
}

Message.closeMessage = function(controller, messageId) {
	controller.serviceRequest(Message.identifier, {
		method: 'messageClose',
		parameters: { 'message':messageId }
	});
}

Message.moveMessage = function(controller, messageId, folderId) {
	controller.serviceRequest(Message.identifier, {
		method: 'messageMove',
		parameters: { 'message':messageId, 'folder':folderId }
	});
}

Message.loadMoreDetail = function(controller, messageId, callback) {
	Mojo.Log.info("Requesting more email body for ", messageId);
	controller.serviceRequest(Message.identifier, {
		method: 'loadMoreDetail',
		parameters: { 'message':messageId },
		onSuccess: callback,
		onFailure: function(err) { Mojo.Log.error("getFolderAndAccount",$H(err).inspect()); }
	});
}

Message.launchAttachment = function(controller, url, error) {
	Mojo.Log.info("launching this ", url);
	controller.serviceRequest("palm://com.palm.applicationManager/open", {
		parameters: { target : 'file://' + url },
		onFailure: error
	});
}

/**
 * Request the specified attachment be downloaded
 * @param {Object} partId
 */
Message.loadAttachment = function(partId, callback, error) {
	return new Mojo.Service.Request(Message.identifier, {
		method: 'loadAttachment',
		parameters: { 'part':partId },
		onSuccess: callback,
		onFailure: error
	});
}

/**
 * Cancel the download request for this attachment
 * @param {Object} partId
 */
Message.cancelLoadAttachment = function(controller, partId, callback, error) {
	controller.serviceRequest(Message.identifier, {
		method: 'cancelLoadAttachment',
		parameters: { 'part':partId },
		onSuccess: callback,
		onFailure: error
	});
}

/**
 * Request the details for a given attachment
 * @param {Object} partId
 */
Message.getAttachmentDetails = function(controller, partId, callback, error) {
	controller.serviceRequest(Message.identifier, {
		method: 'partDetail',
		parameters: { 'part':partId },
		onSuccess: callback,
		onFailure: error
	});
}

/**
 * Retrieve the information for a given resource.
 *
 * @param {String} uri	The URI of the resource to retrieve the information for.
 * @param {String} mimeType	The mimeType of the resource to retrieve the information for.
 * @param {function} callback	Called when call is successful
 * @param {function} error	Called when call fails
 */
Message.getResourceType = function(controller, uri, mimeType, callback, error) {
	var params = {uri: uri};

	if (Message.isValidMimeType(mimeType)) {
		params.mime = mimeType;
	}
	
	controller.serviceRequest('palm://com.palm.applicationManager/getResourceInfo', {
		parameters: params,
		onSuccess: callback,
		onFailure: error
	});
}

/**
 * Open up the attachment with appropriate application using cross-app push scene. If application
 * doesn't support cross-app launch then it will be launched in a separate window.
 * @param {String} uri The resource to stream.
 * @param {String} appid The application id to open.
 * @param {String} mimeType uri mime type.
 */
Message.launchAttachments = function(controller,uri, appid, mimeType) {
	Mojo.Log.info("Email - Launching: '%s' with %s", uri, appid);

	crossAppScene = {
		'com.palm.app.videoplayer': 'nowplaying',
		'com.palm.app.streamingmusicplayer': 'nowplaying'		
	};
	var params = {target: uri, mimeType: mimeType};
	
	//If an App doesn't support cross-app launch then open it in a separate window.
	if (crossAppScene[appid]) {
		var args = { appId: appid, name: crossAppScene[appid] };
		controller.stageController.pushScene(args, params);
	}
	else {
		controller.serviceRequest('palm://com.palm.applicationManager', {
			method: 'open',
			parameters: {
				'id': appid,
				'params': params
			}
		});
	}
}

/**
 * Open up the attachment with appropriate application using cross-app push scene. If application
 * doesn't support cross-app launch then it will be launched in a separate window.
 * @param {String} uri The resource to stream.
 * @param {String} appid The application id to open.
 * @param {String} mimeType uri mime type.
 */
Message.saveAttachment = function(controller, filePath, callback, error) {
	controller.serviceRequest(Message.identifier, {
		method: 'saveAttachment',
		onSuccess: callback,
		onFailure: error,
		parameters: { uri: filePath }
	});
}

/**
 * Check to see if given token is a valid mime type.
 * @param {Object} mimeType
 */

Message.isValidMimeType = function(mimeType)
{
	if(mimeType === undefined || mimeType === null)
		return false;
	
	//Check for "/" present in the mimeType. This at least works for all attachment types we're interested in
	var slashIndex = mimeType.indexOf("/");
	if(slashIndex < 0)
		return false;
	
	return true;	
}

/*
 * for Calendar invites
 */
Message.inviteResponse = function(message, response, callback) {
	//console.log("MojoRequest: requestRespond message="+message.id+", value="+response);
	var prefix = "";
	switch(response) {
		case 'accept':
			prefix = Message.kInviteSubjectPrefixAccpted;
			break;
		case 'tentative':
			prefix = Message.kInviteSubjectPrefixTentative;
			break;
		case 'decline':
			prefix = Message.kInviteSubjectPrefixDeclined;
			break;
	}
	
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'requestRespond',
			parameters:  {
				'message':message.id, 
				'value': response,
				'summary': prefix + message.summary,
				'html': message.isHtml,
				'msg': message.isHtml ? message.text : undefined,
				'text': message.isHtml ? undefined : message.text
			},
			onSuccess: callback
		});
	return request;
}

Message.setRead = function(messageId, value) {
	//console.log("MojoRequest: setRead");
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'setRead',
			parameters: {'message':messageId, 'value': value }
		});
	return request;
}

Message.setDeleted = function(messageId, value, callback, error) {
	Mojo.Log.info("MojoRequest: setDeleted ", messageId);
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'setDeleted',
			parameters: {'message':messageId, 'value': value },
			onSuccess: callback,
			onFailure: error
		});
	return request;
}

Message.setFlagged = function(messageId, value) {
	//console.log("MojoRequest: setFlagged");
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'setFlagged',
			parameters: {'message':messageId, 'value': value }
		});
	return request;
}

Message.setForwarded = function(messageId, value) {
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'setForwarded',
			parameters: {'message':messageId, 'value': value }
		});
	return request;
}

Message.setReplied = function(messageId, value) {
	var request = new Mojo.Service.Request(Message.identifier, {
			method: 'setReplied',
			parameters: {'message':messageId, 'value': value }
		});
	return request;
}

Message.kInviteSubjectPrefixAccpted = $L("Accepted: ");
Message.kInviteSubjectPrefixTentative = $L("Tentative: ");
Message.kInviteSubjectPrefixDeclined = $L("Declined: ");
