package eu.dnetlib.r2d2.neo4j.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;

public class DebugProxy implements java.lang.reflect.InvocationHandler {
	private static Logger logger = Logger.getLogger(DebugProxy.class);

	private Object obj;
	
	public DebugProxy() {
		System.out.println("Initializing... ");
		logger.debug("Initializing... ");
	}

	public static Object newInstance(Object obj) {
		System.out.println("returning new proxy");
		return java.lang.reflect.Proxy.newProxyInstance(obj.getClass()
				.getClassLoader(), obj.getClass().getInterfaces(),
				new DebugProxy(obj));
	}

	private DebugProxy(Object obj) {
		this.obj = obj;
	}

	public Object invoke(Object proxy, Method m, Object[] args)
			throws Throwable {
		Object result;
		try {
			System.out.println("before method " + m.getName());
			result = m.invoke(obj, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		} catch (Exception e) {
			throw new RuntimeException("unexpected invocation exception: "
					+ e.getMessage());
		} finally {
			System.out.println("after method " + m.getName());
		}
		
		return result;
	}
}