/**
 * GetMetadataFieldValueMessageHandler.java
 * Created on May 1, 2009
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.contentmgmt.communication.handlers;

import java.util.List;

import com.tandbergtv.cms.portal.util.transaction.Transactional;
import com.tandbergtv.metadatamanager.model.Asset;
import com.tandbergtv.metadatamanager.model.Field;
import com.tandbergtv.watchpoint.communication.Util;
import com.tandbergtv.watchpoint.pmm.communication.HandlerErrorCode;
import com.tandbergtv.watchpoint.pmm.communication.MessageHandler;
import com.tandbergtv.watchpoint.pmm.communication.MessageHandlerException;
import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.title.ITitlePersistenceService;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.message.IMessageKey;
import com.tandbergtv.workflow.message.IMessageUID;
import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowMessage.MessageType;

/**
 * @author Vlada Jakobac
 * 
 */
public class GetMetadataFieldValueMessageHandler implements MessageHandler {

	private static final String FIELD_VALUE = "fieldValue";
	private static final String TTV_X_PATH = "ttvXPath";
	private static final String ITEM_TYPE = "itemType";
	private static final String TITLE_ID = "titleId";
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tandbergtv.watchpoint.pmm.communication.MessageHandler#handleMessage
	 * (com.tandbergtv.workflow.message.WorkflowMessage)
	 */
	@Override
	@Transactional
	public WorkflowMessage handleMessage(WorkflowMessage message)
			throws Exception {
		Util.validateRequired(message, TITLE_ID, TTV_X_PATH, ITEM_TYPE);

		/* Get the input variables */
		Long titleId = Util.getLongValue(message, TITLE_ID);
		String ttvXPath = Util.getStringValueTrimmed(message, TTV_X_PATH);
		String itemType = Util.getStringValueTrimmed(message, ITEM_TYPE);

		/* Get the Service Registry to allow fetching of the title */
		ServiceRegistry registry = ServiceRegistry.getDefault();
		ITitlePersistenceService service = registry
				.lookup(ITitlePersistenceService.class);

		/* Get the Title using the Service */
		Title title = null;
		try {
			title = service.get(titleId);
		} catch (Exception e) {
			String msg = "Failed to read the Title from the persistence service, error: "
					+ e.getMessage();
			throw new MessageHandlerException(
					HandlerErrorCode.OBJECT_NOT_PRESENT, msg, e);
		}

		if (title == null) {
			String msg = "Did not get a Title from the persistence service.";
			throw new MessageHandlerException(
					HandlerErrorCode.OBJECT_NOT_PRESENT, msg);
		}

		/* Get the matching asset from the title */
		Asset groupAsset = title.getAsset();
		if (groupAsset == null) {
			String msg = "Did not get a group object for a given title.";
			throw new MessageHandlerException(
					HandlerErrorCode.OBJECT_NOT_PRESENT, msg);
		}

		/* Find all fields for a given itemType and ttvXPath */
		List<Field> fields = null;
		Asset targetAsset = null;
		if (groupAsset.getAssetType().equals(itemType))
			targetAsset = groupAsset;
		else {
			for (Asset asset : groupAsset.getAllDescendantItems(true)) {
				if (asset.getAssetType().equals(itemType)) {
					targetAsset = asset;
					break;
				}
			}
		}
		
		if (targetAsset == null) {
			String msg = "Did not get an item object of a given itemType.";
			throw new MessageHandlerException(
					HandlerErrorCode.OBJECT_NOT_PRESENT, msg);
		}
		fields = targetAsset.getAllFieldsForXpath(itemType, ttvXPath);

		String result = "";
		if (fields != null && fields.size() > 0)
			result = fields.get(0).getValue();

		/* Build the response Workflow Message */
		IMessageUID uid = message.getMessageUID();
		IMessageKey key = message.getKey();
		WorkflowMessage response = new WorkflowMessage(uid, key,
				MessageType.ack);
		response.putValue(FIELD_VALUE, result);

		return response;
	}

}
