/**
 * CatcherGroupDispatcher.java
 * Created on Jul 23, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.workflow.adaptor.dispatcher;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.rmi.RemoteException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.systinet.wsdl.com.n2bb.manager.webservice.common.Catcher;
import com.systinet.wsdl.com.n2bb.manager.webservice.common.CatcherGroup;
import com.systinet.wsdl.com.n2bb.manager.webservice.server.SchedulerService;
import com.systinet.wsdl.com.n2bb.manager.webservice.server.SchedulerService_getCatcherGroups_comN2BbManagerWebserviceCommonServiceException_Fault;
import com.tandbergtv.workflow.adaptor.conf.IDispatcherConfiguration;
import com.tandbergtv.workflow.comm.IDestination;
import com.tandbergtv.workflow.message.IMessage;
import com.tandbergtv.workflow.message.MessageKeyImpl;
import com.tandbergtv.workflow.message.MessageUIDImpl;
import com.tandbergtv.workflow.message.WorkflowMessage;
import com.tandbergtv.workflow.message.WorkflowPayload;
import com.tandbergtv.workflow.message.WorkflowMessage.MessageType;
import com.tandbergtv.workflow.util.XMLDocumentUtility;

/**
 * @author Vlada Jakobac
 * 
 */
public class CatcherGroupDispatcher extends MediaPathDispatcher {

	private static final Logger logger = Logger
			.getLogger(CatcherGroupDispatcher.class);

	/**
	 * Class Constructor
	 * 
	 * @param conf
	 *            Dispatcher Configuration
	 * @param destination
	 *            The target Destination
	 */
	public CatcherGroupDispatcher(IDispatcherConfiguration conf,
			IDestination destination) {
		super(conf, destination);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tandbergtv.workflow.adaptor.dispatcher.IDispatcher#send(com.tandbergtv.workflow.message.IMessage)
	 */

	protected WorkflowMessage generateResponse(IMessage msg, URL url)
			throws DispatcherException {
		logger.debug("payload=" + msg.getPayload().getContent());
		Document doc;
		try {
			doc = XMLDocumentUtility.loadXml(msg.getPayload().getContent());
			String catcherGroupName = null;
			XPath xpath = XPathFactory.newInstance().newXPath();
			Node parameterListNode = (Node) xpath.evaluate(
					"//WFSMessage/MessageBody/ParameterList", doc,
					XPathConstants.NODE);
			if (parameterListNode != null) {
				Node catcherGroupNameNode = (Node) xpath.evaluate(
						"Parameter[@Name='CatcherGroupName']",
						parameterListNode, XPathConstants.NODE);
				if (catcherGroupNameNode != null) {
					catcherGroupName = (String) xpath.evaluate("Value",
							catcherGroupNameNode, XPathConstants.STRING);
				}
			}
			
			Node wfsMessageNode = (Node) xpath.evaluate("//WFSMessage", doc,
					XPathConstants.NODE);

			String messUID = (String) wfsMessageNode.getAttributes()
					.getNamedItem("UID").getTextContent();
			String requestKey = (String) wfsMessageNode.getAttributes()
					.getNamedItem("RequestKey").getTextContent();
			logger.debug("messUID=" + messUID + ", requestKey=" + requestKey);
			WorkflowMessage response = new WorkflowMessage(new MessageUIDImpl(
					messUID), new MessageKeyImpl(requestKey));
			WorkflowPayload payload = (WorkflowPayload) response.getPayload();

			try {
				/* Make the proxy call to the webservice */
				SchedulerService service = getService(url);
				String catcherIds = getCatcherIds(service, catcherGroupName);
				payload.putValue("CatcherIds", catcherIds);
				response.setType(MessageType.ack);
			} catch (MediaPathAPIException de) {
				logger.error("Error occurred whilce getting CatcherIds: ", de);
				StringWriter writer = new StringWriter();
				de.printStackTrace(new PrintWriter(writer));
				payload.putValue("error-message", de.getMessage());
				payload.putValue("error-stack", writer.toString());
				response.setType(MessageType.nack);

			}
			return response;

		} catch (Exception e) {
			throw new DispatcherException(e);
		}

	}

	private String getCatcherIds(SchedulerService service,
			String catcherGroupName) throws MediaPathAPIException {

		String catcherIds = "";
		Catcher[] catchers = null;
		CatcherGroup[] catcherGroups;
		try {
			catcherGroups = service.getCatcherGroups();
		} catch (SchedulerService_getCatcherGroups_comN2BbManagerWebserviceCommonServiceException_Fault e) {
			throw new MediaPathAPIException(e);
		} catch (RemoteException e) {
			throw new MediaPathAPIException(e);
		}
		for (int i = 0; i < catcherGroups.length; i++) {
			if (catcherGroups[i].getName().equalsIgnoreCase(catcherGroupName)) {
				catchers = catcherGroups[i].getCatchers();
				break;
			}
		}

		if (catchers != null) {
			for (int j = 0; j < catchers.length; j++) {
				catcherIds += catchers[j].getId().toString() + ",";
			}
			// remove the last comma
			catcherIds = catcherIds.substring(0, catcherIds.length() - 1);
			logger.debug("catcherIds=" + catcherIds);
		}

		return catcherIds;
	}

}
