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.TitlePropertyManager;
import com.tandbergtv.watchpoint.pmm.entities.TitleProperty;
import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowMessage.MessageType;

/**
 * Message Handler for "Retrieve Info" message.
 * 
 * @author Raj Prakash
 */
public class RetrieveInfoMessageHandler implements MessageHandler {
	private static final String NAME = "name";
	private static final String TITLE_ID = "titleId";
	private static final String SCHEDULE_ID = "scheduleId";
	private static final String CONTEXT_ID = "contextId";
	
	private static final String STATUS = "status";
	private static final String STATUS_SUCCESS = "SUCCESS";
	private static final String STATUS_FAILURE = "FAILURE";
	private static final String VALUE = "value";
	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) {
		Util.validateRequired(message, NAME, TITLE_ID);

		String name = Util.getStringValueTrimmed(message, NAME);
		long titleId = Util.getLongValue(message, TITLE_ID);
		if(titleId < 1)
			throw new IllegalArgumentException(TITLE_ID + " has to be greater than zero");
		Long assetListId = Util.convertZeroOrLessToNull(Util.getLongValue(message, SCHEDULE_ID));
		Long contextId = Util.convertZeroOrLessToNull(Util.getLongValue(message, CONTEXT_ID));
		
		TitleProperty foundProperty = TitlePropertyManager.getInstance().retrieve(name, titleId,
				assetListId, contextId);

		WorkflowMessage response = new WorkflowMessage(message.getMessageUID(), message.getKey(),
				MessageType.ack);
		
		if(foundProperty != null) {
			response.putValue(STATUS, STATUS_SUCCESS);
			String value = foundProperty.getValue() != null
								? foundProperty.getValue() : EMPTY_STRING;
			response.putValue(VALUE, value);
		} else {
			response.putValue(STATUS, STATUS_FAILURE);
			response.putValue(VALUE, EMPTY_STRING);
		}
		
		return response;
	}

}
