/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.pool.connection;

import java.lang.reflect.Method;
import java.sql.SQLException;

import org.huihoo.jfox.pool.PoolableObjectInvocationHandler;
import org.huihoo.jfox.pool.PoolableObject;

/**
 * 
 * @author <a href="mailto:kelvin_wym@hotmail.com">Kelvin Wu</a>
 */

public class PoolableConnectionInvocationHandler extends PoolableObjectInvocationHandler {

  public PoolableConnectionInvocationHandler(PoolableObject poolableObject) {
    super(poolableObject);
    if(!(poolableObject instanceof PoolableConnection)) {
      throw new RuntimeException(poolableObject + " is not a PoolableConnection");
    }
  }

  public Object invoke(Object proxy, Method method, Object[] args)
          throws Throwable {

    PoolableConnection pconn = (PoolableConnection)this.getPoolableObject();

    // 拦截 close 方法，并没有关闭连接，而是把 PoolableConnect 设为 false use, 并且返回连接池
    if (method.getName().equals("close") && method.getParameterTypes().length == 0) {
//      pconn.setUsing(false);
//      ObjectPool pool = pconn.getPool();
//      pool.restoreObject(pconn);
      pconn.close();
      return null;
    }
    else {
      Object obj = null;
//      System.out.println("Handle: " + method.getName());
      try {
        // 如果调用的是 PoolableConnetion 本身的方法，比如：activate 并不转交给 java.sql.Connection 执行
        pconn.getClass().getMethod(method.getName(),method.getParameterTypes());
        obj = method.invoke(pconn,args);
//        System.out.println("Handle Method: " + method.getName());
      }
      catch(Exception e){ // PoolableConnection 没有该方法，交给 Connection 执行
        if (!pconn.isUsing()) {
          throw new SQLException("The connection has been closed");
        }
        obj = method.invoke(pconn.getConnection(), args);
      }
      return obj;
    }
  }
}
