package demo;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.module.client.MuleClient;
import org.mule.module.client.RemoteDispatcher;
import org.mule.transport.NullPayload;

/*
 * MuleClient if a helper class for sending messages Mule
 */
public class MuleClientUtils {
	private static Log logger = LogFactory.getLog(MuleClientUtils.class);
	private static String muleEndpoint = "tcp://localhost:60504";

	/*
	 * sends a message of any type to the specified endpoint
	 * for testing the ESB Demo
	 */
	@SuppressWarnings("unchecked")
	public static Object sendMessage(String endpoint, Object message,
			Class expectedResultClass, Map headerProperties) {
		try {
			// grab a new MuleClient and RemoteDispatcher
			MuleClient client = new MuleClient(false);
			RemoteDispatcher dispatcher = client.getRemoteDispatcher(muleEndpoint);

			// send the message and check the result
			MuleMessage m = dispatcher.sendRemote(endpoint, message, headerProperties);
			if (null == m || m.getPayload() instanceof NullPayload) {
				if (null != expectedResultClass) {
					String nullMsg = (null == m) ? "null" : "NullPayload";
					logger.warn("sendMessage: ***** " + nullMsg
							+ " returned from request: returning early");
				}
				return null;
			}

			// okay, cool, we got something
			Object payload = m.getPayload();
			if (!expectedResultClass.isAssignableFrom(payload.getClass())) {
				logger.warn("sendMessage: ***** returned payload is not of expected type: expected ["
						+ expectedResultClass + "], but got [" + payload.getClass() + "]");
				// for now, just return what we got and make the caller handle it
			}

			logger.debug("sendMessage: results: " + payload);

			return payload;

		} catch (MuleException e) {
			logger.warn("sendMessage: caught MuleException: returning null", e);
		}

		return null;
	}

}