package com.tandbergtv.watchpoint.pmm.communication.handlers;

import com.tandbergtv.watchpoint.communication.Util;
import com.tandbergtv.watchpoint.pmm.communication.MessageHandler;
import com.tandbergtv.watchpoint.pmm.core.AssetMapInfo;
import com.tandbergtv.watchpoint.pmm.core.IPMMService;
import com.tandbergtv.watchpoint.pmm.core.PMMException;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowMessage.MessageType;

/**
 * Message Handler for "Map Asset to Title" message.
 * 
 * @author Raj Prakash
 */
public class MapAssetMessageHandler implements MessageHandler {
	
	private static final String ASSET_PATH = "assetPath";
	private static final String SOURCE_COMPONENT_NAME = "sourceComponentName";
	private static final String SOURCE_ENTITY_NAME = "sourceEntityName";
	private static final String SOURCEID = "sourceId";

	private static final String STATUS = "status";
	private static final String MAP_RESPONSE_STATUS_MAPPED = "Map Successful";
	private static final String MAP_RESPONSE_STATUS_NOTMAPPED = "Manual Mapping Required";

	private static final String MESSAGE = "message";
	private static final String FAILURE_MESSAGE_NO_MATCH = "No matching titles found";
	private static final String FAILURE_MESSAGE_MULTIPLE_MATCHES = "Multiple matching titles found";
	
	private static final String MAPPED_TITLES = "mappedTitles";

	private static final String EMPTY_STRING = "";


	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.communication.MessageHandler#handleMessage(com.tandbergtv.workflow.message.WorkflowMessage)
	 */
	public WorkflowMessage handleMessage(WorkflowMessage message) throws PMMException {
		Util.validateRequired(message, ASSET_PATH);
		
		IPMMService pmmService = ServiceRegistry.getDefault().lookup(IPMMService.class);
		AssetMapInfo mapInfo = pmmService.assetArrived(
				Util.getStringValueTrimmed(message, ASSET_PATH),
				Util.getStringValueTrimmed(message, SOURCE_COMPONENT_NAME),
				Util.getStringValueTrimmed(message, SOURCE_ENTITY_NAME),
				Util.getStringValueTrimmed(message, SOURCEID));

		WorkflowMessage response = new WorkflowMessage(message.getMessageUID(), message.getKey(),
				MessageType.ack);
		
		if(mapInfo.getStatus() == AssetMapInfo.Status.MATCHED_TITLE_UPDATED) {
			response.putValue(STATUS, MAP_RESPONSE_STATUS_MAPPED);
			response.putValue(MESSAGE, EMPTY_STRING);
		} else {
			response.putValue(STATUS, MAP_RESPONSE_STATUS_NOTMAPPED);
			response.putValue(MESSAGE,
									(mapInfo.getStatus() == AssetMapInfo.Status.NO_MATCH)
									? FAILURE_MESSAGE_NO_MATCH
									: FAILURE_MESSAGE_MULTIPLE_MATCHES);
		}
		response.putValue(MAPPED_TITLES, mapInfo.getMappedTitles());
		
		return response;
	}
	
	
	
}
