/* 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.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;

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

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

public class ConnectionFactory extends ProxyObjectFactory {
  private String dbDriver = null; // database dirver class name
  private String dbURL = null; // database url
  private String user = null; // database user name.
  private String password = null; // database password

  public ConnectionFactory(Class classType, Class invokerClass) throws Exception {
    super(classType, invokerClass);
  }

  public PoolableObject makeObject() throws Exception {
    // 建立实际的连接
    Class.forName(dbDriver);
//    System.out.println("dbURL: " + dbURL);
    Connection conn = DriverManager.getConnection(dbURL, user, password);

    // 生成 PoolableConnection
    PoolableConnection pconn = (PoolableConnection)classType.getConstructor(new Class[]{Connection.class}).newInstance(new Object[]{conn});

    // 生成 PoolableConnectionInvocationHandler
    InvocationHandler handler = (InvocationHandler)invokerClass.getConstructor(new Class[]{PoolableObject.class}).newInstance(new Object[]{pconn});

    return (PoolableObject)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                                                  new Class[]{Connection.class,PoolableConnection.class},
                                                  handler);

  }

  /**
   * destroy the poolConnection in pool.
   * @param object
   * @throws Exception
   */
  public void destroyObject(PoolableObject object) throws Exception {
//    System.out.println("ConnectionFactory.destroyObject");
    ((org.huihoo.jfox.pool.connection.PoolableConnection) object).reallyClose();
    object.passivate();
    super.destroyObject(object);
  }

  /**
   * Set database driver name.
   * @param dbDriver
   */
  void setDbDriver(String dbDriver) {
    this.dbDriver = dbDriver;
  }

  /**
   * Set database url
   * @param dbURL
   */
  void setDbURL(String dbURL) {
    this.dbURL = dbURL;
  }

  /**
   * Set user name.
   * @param user
   */
  void setUser(String user) {
    this.user = user;
  }

  /**
   * Set password.
   * @param password
   */
  void setPassword(String password) {
    this.password = password;
  }

  String getDbDriver() {
    return dbDriver;
  }

  String getDbURL() {
    return dbURL;
  }

  String getUser() {
    return user;
  }

  String getPassword() {
    return password;
  }
}
