/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.util;

import java.lang.reflect.Method;

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

/**
 * Utility to log input params to method calls.
 * 
 * @author DNS   BOHMEG
 */
public class ParameterInterceptor extends SimpleTraceInterceptor {
	
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 3265481604594992957L;

	protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
		try {
			if(logger.isDebugEnabled())
				logParameters(invocation.getMethod(), invocation.getArguments(), logger);
			return invocation.proceed();
		}
		catch (Throwable ex) {
			if(logger.isErrorEnabled())
				logger.error("Exception thrown in: " +  getInvocationDescription(invocation), ex);
			throw ex;
		}
	}
	
	private void logParameters(Method method, Object[] args, Log logger) {
		String methodName = method.getName();
		if (args == null || args.length == 0) {
			logger.debug("....Calling: " + methodName + "() with no paramters.");
			return;
		}

		logger.debug("...Calling: " + methodName + "(...) with params,");
		Object arg = null;
		Object item = null;
		for (int i = 0; i < args.length; i++) {
			arg = args[i];
			if (arg == null) {
				logger.debug("\t    param [" + i + "]: null");
			} else {
				if (arg instanceof Object[]) {
					logger.debug("array param:");
					for (int j = 0; j < ((Object[]) arg).length; j++) {
						item = ((Object[]) arg)[j];
						if (item == null) {
							logger.debug("\t\tnull");
						} else {
							logger.debug("\t\t" + item);
						}
					}
				} else {
					logger.debug("\t    param [" + i + "]: " + arg);
				}
			}
			i++;
		}
	}
}
