/*
 * Copyright: (c) TBEE.ORG
 * Version:   $Revision: 1.1 $
 * Modified:  $Date: 2007/06/05 13:07:29 $
 * By:        $Author: toeukpap $
 */
package nl.reinders.jdbc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

import org.tbee.util.JdbcUtil;
import org.tbee.util.pool.JdbcConnectionPoolDataSource;

class ReindersInformixConnection implements InvocationHandler
	{
		// ==============================================================================================================================
		// CONSTRUCTOR
		
		/**
		 * @param connection
		 * @param objectPool
		 */
		public ReindersInformixConnection(java.sql.Connection connection)
		{
			iConnection = connection;
		}
		private java.sql.Connection iConnection = null;
		
		// ==============================================================================================================================
		// CONNECTION
		
		/**
		 * 
		 */
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
		{
			try
			{
				// just invoke it
				return method.invoke(iConnection, args);
			}
			catch (InvocationTargetException e)
			{
		    	if (JdbcConnectionPoolDataSource.log4j.isInfoEnabled()) JdbcConnectionPoolDataSource.log4j.info(method.getName() + ": " + e + "->" + e.getCause());
		    	throw e.getCause();
			}
			finally
			{
				// make sure the constraints are set to deferred
				if ( method.getName().equals("commit") 
				  || method.getName().equals("rollback")
				  || ( method.getName().equals("setAutoCommit") && ((Boolean)args[0]).booleanValue() == false ) 
				   )
				{
					JdbcUtil.execute(iConnection, "set constraints all deferred");
				}
			}			
		}
		
		// ==============================================================================================================================
		// CONVENIENCE
		
		/**
		 * Wrap a regular connection in a PooledConnection
		 */
		static java.sql.Connection wrap(java.sql.Connection connection)
		{
			ReindersInformixConnection lConnection = new ReindersInformixConnection(connection);
	    	return (java.sql.Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { java.sql.Connection.class }, lConnection);
		}
	}