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.ProgressManager;
import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowMessage.MessageType;

/**
 * Message Handler for "Update Material Progress Status" message.
 * 
 * @author Raj Prakash
 */
public class UpdateMaterialProgressMessageHandler implements MessageHandler {

	private static final String TITLE_ID = "titleId";
	private static final String SCHEDULE_ID = "scheduleId";
	private static final String STATUS = "status";
	private static final String VALUE = "value";
	private static final String SUCCESS = "success";
	private static final String SOURCE_COMPONENT_NAME = "sourceComponentName";
	private static final String SOURCE_ENTITY_NAME = "sourceEntityName";
	private static final String SOURCEID = "sourceId";

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.communication.MessageHandler#handleMessage(com.tandbergtv.workflow.message.WorkflowMessage)
	 */
	public WorkflowMessage handleMessage(WorkflowMessage message) {
		
		Util.validateRequired(message, TITLE_ID, STATUS, SUCCESS);
		
		long titleId = Util.getLongValue(message, TITLE_ID);
		if(titleId < 1)
			throw new IllegalArgumentException(TITLE_ID + " has to be greater than zero");
		
		ProgressManager.newInstance().updateStatus(
				titleId,
				Util.convertZeroOrLessToNull(Util.getLongValue(message, SCHEDULE_ID)),
				Util.getStringValueTrimmed(message, STATUS),
				Util.getStringValueTrimmed(message, VALUE),
				Util.getBooleanValue(message, SUCCESS),
				Util.getStringValueTrimmed(message, SOURCE_COMPONENT_NAME),
				Util.getStringValueTrimmed(message, SOURCE_ENTITY_NAME),
				Util.getStringValueTrimmed(message, SOURCEID));
		
		return new WorkflowMessage(message.getMessageUID(), message.getKey(), MessageType.ack);
	}

}
