package com.ruoyi.ext.api.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.stat.DruidDataSourceStatManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;

@SuppressWarnings("unchecked")
public class DBFactory {
    private static HashMap dbImplMap = new HashMap();

    private static DBImpl defaultImpl = null;
    private static boolean dbinitialized = false;




    private static final Log logger = LogFactory.getLog(DBFactory.class);

    private DBFactory()
    {
        dbinit();
    }



    private static DBImpl loadDBImpl(String dsName, DruidDataSource datasource)
    {
        DBImpl dbAccessImpl = null;
        dbAccessImpl = DBImpl.getInstance(dsName, datasource);
        return dbAccessImpl;
    }

    private static synchronized void dbinit()
    {
        if (dbinitialized) return;
        int i=0;

        DBImpl dbAccessImpl = null;

        try
        {
        for(DruidDataSource datasource : DruidDataSourceStatManager.getDruidDataSourceInstances()){

            String poolname= datasource.getName();
            if (i==0) {
                defaultImpl = loadDBImpl(poolname, datasource);
                dbImplMap.put(poolname, defaultImpl);
            }
            else
            {
                dbAccessImpl = loadDBImpl(poolname, datasource);
                dbImplMap.put(poolname, dbAccessImpl);
            }
            i++;

        }
        } catch (Exception e)
        {
            logger.fatal("数据源初始化失败：" + e);
        }


        dbinitialized = true;
    }

    public static final DBImpl getDBImpl()
    {
        if (!dbinitialized) dbinit();
        return defaultImpl;
    }

    public static final DBImpl getDBImpl(String dsName)
    {
        if (!dbinitialized) dbinit();
        if (dsName == null || dsName.length()<=0) return defaultImpl;
        return (DBImpl) dbImplMap.get(dsName);
    }
}
