package nl.nikhef.tools;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class InvocationLogProxy  implements InvocationHandler {


	private final Object _delegate;
	private final String _className;

	private InvocationLogProxy(final Object delegate) {
		_delegate = delegate;
		_className = delegate.getClass().getSimpleName();
	}
		  
	public static final <T> T wrap(T object, Class<T> iface)
	{
		return iface.cast( Proxy.newProxyInstance(iface.getClassLoader(), new Class[] { iface }, new InvocationLogProxy(object)) );
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.printf("%9d %s.%s(%s)\n", System.currentTimeMillis(), _className, method.getName(), Arrays.toString(args));
		try
		{
			final Object ret = method.invoke(_delegate, args);
			System.out.printf("%9d -> return: %s\n", System.currentTimeMillis(), ret);
			return ret;
		} catch (InvocationTargetException t) {
			System.out.printf("%9d -> thrown: %s\n", System.currentTimeMillis(), t.getTargetException());
			throw t;
		}
	}

}
