/**
 * DeleteTitleMessageHandler.java
 * Created on Jun 25, 2009
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.contentmgmt.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.title.ITitlePersistenceService;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
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;

/**
 * @author Vlada Jakobac
 * 
 */
public class DeleteTitleMessageHandler implements MessageHandler {

	private static final String TITLE_ID = "titleId";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tandbergtv.watchpoint.pmm.communication.MessageHandler#handleMessage
	 * (com.tandbergtv.workflow.message.WorkflowMessage)
	 */
	@Override
	public WorkflowMessage handleMessage(WorkflowMessage message)
			throws Exception {

		Util.validateRequired(message, TITLE_ID);

		/* Get the title Id */
		Long titleId = Util.getLongValue(message, TITLE_ID);

		/* Get the Service Registry to allow fetching of the title */
		ServiceRegistry registry = ServiceRegistry.getDefault();
		ITitlePersistenceService service = registry
				.lookup(ITitlePersistenceService.class);

		try {
			service.delete(titleId);
		} catch (Exception e) {
			String msg = "Failed to delete the Title, error: " + e.getMessage();
			throw new MessageHandlerException(HandlerErrorCode.RUNTIME_ERROR,
					msg, e);
		}

		/* Build the response Workflow Message */
		IMessageUID uid = message.getMessageUID();
		IMessageKey key = message.getKey();
		WorkflowMessage response = new WorkflowMessage(uid, key,
				MessageType.ack);

		return response;
	}

}
