package gov.va.med.esr.messaging.util;

import gov.va.med.fw.hl7.Message;
import gov.va.med.fw.util.StopWatchLogger;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;

public class InboundMessagePerformanceMonitorInterceptor extends
		PerformanceMonitorInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9210795483570139722L;

	public InboundMessagePerformanceMonitorInterceptor() {
	}

	/**
	 * Create a new InboundMessagePerformanceMonitorInterceptor with a dynamic or
	 * static logger, according to the given flag.
	 * 
	 * @param useDynamicLogger
	 *           whether to use a dynamic logger or a static logger
	 * @see #setUseDynamicLogger
	 */
	public InboundMessagePerformanceMonitorInterceptor(boolean useDynamicLogger) {
		super(useDynamicLogger);
	}

	/**
	 * @see org.springframework.aop.interceptor.PerformanceMonitorInterceptor#invokeUnderTrace(org.aopalliance.intercept.MethodInvocation,
	 *      org.apache.commons.logging.Log)
	 */
	protected Object invokeUnderTrace(MethodInvocation invocation, Log logger)
			throws Throwable {

		StopWatchLogger stopWatch = null;
		Message message = null;

		try {
			Object[] arguments = invocation.getArguments();
			message = (Message) arguments[0];

			String name = createInvocationTraceName(invocation);

			if (message != null) {
				stopWatch = new StopWatchLogger(new StringBuffer(message.getType())
						.append("-").append(name).toString());
				if (stopWatch != null) {
					stopWatch.start();
				}

				StopWatchLogger stopWatch1 = null;
				stopWatch1 = new StopWatchLogger(
						new StringBuffer(message.getType()).append("-").append(
								"Start inbound message processing - ").toString());
				stopWatch1.start();
				stopWatch1.stopAndLog(new StringBuffer("Id ").append(
						message.getMessageID()).toString());
			}

			// Make method invocation
			Object obj = invocation.proceed();

			return obj;
		}
		finally {
			StringBuffer info = new StringBuffer("Total time to process Id ")
					.append(message.getMessageID());
			if (stopWatch != null) {
				stopWatch.stopAndLog(info.toString(), logger);
			}
		}
	}
}
