package com.tohi.com.tohi.system.db;

import com.tohi.common.pwdutil.PropertiesConfigurerUtil;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public  abstract class Pool {
    public String propertiesName ="connection-INF.properties";
    private static Pool instance= null;// 定义唯一实例
    protected int maxConnect = 108;// 最大连接数
    protected int normalConnect = 18;// 保持连接数
    protected String driverName =null;// 驱动字符串
    protected Driver driver = null;// 驱动变量

    // 私有构造函数，不允许外界访问
    protected Pool() {
        try {
            init();
            loadDrivers(driverName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        private void init() throws IOException {
            this.driverName= PropertiesConfigurerUtil.getProperty("driverName");
            this.maxConnect = Integer.parseInt(PropertiesConfigurerUtil.getProperty("maxConnect"));
            this.normalConnect =Integer.parseInt(PropertiesConfigurerUtil.getProperty("normalConnect"));
        }

    protected void loadDrivers(String driverClassName) {
        try{
            driver = (Driver) Class.forName(driverClassName).newInstance();
            DriverManager.registerDriver(driver);
            System.out.println("成功注册JDBC驱动程序"+ driverClassName);
        } catch (Exception e){
            System.out.println("无法注册JDBC驱动程序:"+ driverClassName +",错误:"+e);
        }
    }

    public abstract void createPool();

    public static synchronized Pool getInstance() throws IOException,InstantiationException,
            IllegalAccessException,
            ClassNotFoundException {
        if(instance == null){
            instance.init();
            instance = (Pool)Class.forName("com.luchang.system.common.db.Pool").newInstance();
        }
        return  instance;
    }

    //获得一个可用的连接，如果没有则创建一个连接，且小于最大连接限制
    public abstract Connection getConnection();

    // 获得一个连接，有时间限制
    public abstract Connection getConnection(long time);


    // 将连接对象返回给连接池
    public abstract void freeConnection(Connection con);

    // 返回当前空闲连接数
    public abstract int getnum();
    //返回当前工作的连接数
    public abstract int getnumActive();
    protected synchronized void release() {
        // 撤销驱动
        try{
            DriverManager.deregisterDriver(driver);
            System.out.println("撤销JDBC驱动程序"+ driver.getClass().getName());
        }catch (SQLException e){
            System.out.println("无法撤销JDBC驱动程序的注册:"+ driver.getClass().getName());
        }
    }
}
