package com.tandbergtv.watchpoint.pmm.communication.handlers;

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.ContainerProperty;
import com.tandbergtv.watchpoint.pmm.entities.Context;
import com.tandbergtv.watchpoint.pmm.util.ContextManager;
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;

/**
 * Handler that is responsible for retrieving the value of a property with the
 * given name associated with the given context id.
 * 
 * @author spuranik
 * 
 */
public class GetNamedContainerProperty implements MessageHandler {

	/* variable names in the message */
	private String CONTEXT_ID = "contextId";
	private String PROPERTY_NAME = "name";
	private String PROPERTY_VALUE = "value";
	
	/* error messages */
	private String CONTEXT_NOT_FOUND = "Entity associated with the given context does not exist.";
	private String PROPERTY_NOT_FOUND = "Named property does not not exist for the given context."; 

	@Override
	public WorkflowMessage handleMessage(WorkflowMessage message)
			throws Exception {
		/* validate the message */
		Util.validateRequired(message, CONTEXT_ID, PROPERTY_NAME);
		
		/* extract info from the message */
		Long contextId = Util.getLongValue(message, CONTEXT_ID);
		String propertyName = Util.getStringValueTrimmed(message, PROPERTY_NAME);

		Context context = ContextManager.getInstance().getContext(contextId);
		if(context == null) {
			throw new MessageHandlerException(HandlerErrorCode.OBJECT_NOT_PRESENT, CONTEXT_NOT_FOUND);
		}
		
		ContainerProperty property = context.propertyExists(propertyName);
		if(property == null) {
			throw new MessageHandlerException(HandlerErrorCode.OBJECT_NOT_PRESENT, PROPERTY_NOT_FOUND);
		}
		
		/* Build the response Workflow Message */
		IMessageUID uid = message.getMessageUID();
		IMessageKey key = message.getKey();
		WorkflowMessage response = new WorkflowMessage(uid, key, MessageType.ack);
		// Note: properties are single valued.
		response.putValue(PROPERTY_VALUE, property.getValue());

		return response;
	}

}
