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 "Store Info" message.
 * 
 * @author Raj Prakash
 */
public class StoreInfoMessageHandler 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 VALUE = "value";
	
	/* (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");
		String value = Util.getStringValueTrimmed(message, VALUE);
		Long assetListId = Util.convertZeroOrLessToNull(Util.getLongValue(message, SCHEDULE_ID));
		Long contextId = Util.convertZeroOrLessToNull(Util.getLongValue(message, CONTEXT_ID));
		
		TitleProperty property = new TitleProperty();
		property.setName(name);
		property.setValue(value);
		property.setTitleId(titleId);
		property.setAssetListId(assetListId);
		property.setContextId(contextId);

		TitlePropertyManager.getInstance().store(property);

		return new WorkflowMessage(message.getMessageUID(), message.getKey(), MessageType.ack);
	}

}
