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.IPMMService;
import com.tandbergtv.watchpoint.pmm.core.MetadataMapInfo;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowMessage.MessageType;

/**
 * Message Handler for "Map Metadata to Title" message.
 * 
 * @author Raj Prakash
 */
public class MapMetadataMessageHandler implements MessageHandler {
	
	private static final String METADATA_PATH = "metadataPath";
	private static final String SPECIFICATION = "specification";
	private static final String CREATE_IF_NOT_EXIST = "createIfNotExist";
	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 MAPPED_TITLES = "mappedTitles";

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.communication.MessageHandler#handleMessage(com.tandbergtv.workflow.message.WorkflowMessage)
	 */
	public WorkflowMessage handleMessage(WorkflowMessage message) throws Exception {
		
		Util.validateRequired(message, METADATA_PATH, CREATE_IF_NOT_EXIST);
		
		String specification = Util.getStringValueTrimmed(message, SPECIFICATION);
		String metadataFilePath = Util.getStringValueTrimmed(message, METADATA_PATH);
		boolean createIfNotExist = Util.getBooleanValue(message, CREATE_IF_NOT_EXIST);
		String componentName = Util.getStringValueTrimmed(message, SOURCE_COMPONENT_NAME);
		String entityName = Util.getStringValueTrimmed(message, SOURCE_ENTITY_NAME);
		String sourceId = Util.getStringValueTrimmed(message, SOURCEID);
		
		IPMMService pmmService = ServiceRegistry.getDefault().lookup(IPMMService.class);
		MetadataMapInfo mapInfo = pmmService.metadataArrived(specification, metadataFilePath,
				createIfNotExist, componentName, entityName, sourceId);
		
		WorkflowMessage response = new WorkflowMessage(message.getMessageUID(), message.getKey(),
				MessageType.ack);
		
		if(mapInfo.getStatus() == MetadataMapInfo.Status.TITLES_NOT_FOUND) {
			response.putValue(STATUS, MAP_RESPONSE_STATUS_NOTMAPPED);
		} else {
			response.putValue(STATUS, MAP_RESPONSE_STATUS_MAPPED);
		}
		response.putValue(MAPPED_TITLES, mapInfo.getMappedTitles());
		
		return response;
	}
	
}
