package com.izouma.awesomeadmin.datasource;

import com.izouma.awesomeadmin.model.DataSourceInfo;
import com.izouma.awesomeadmin.util.Const;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final Map targetDataSource = new HashMap<>();
    protected DataSource masterDataSource;


    @Override
    protected DataSource determineTargetDataSource() {
        // 根据数据库选择方案，拿到要访问的数据库
        String dataSourceName = determineCurrentLookupKey();
        if (!dataSourceName.equals("dataSource")) {
            DataSource datasource = (DataSource) targetDataSource.get(DynamicDataSourceHolder.getDataSource());
            if (datasource == null) {
                datasource = createDataSource(DynamicDataSourceHolder.getDataSource());
                targetDataSource.put(DynamicDataSourceHolder.getDataSource(), datasource);
            }
            return datasource;
        } else {
            return masterDataSource;
        }

    }

    @Override
    protected String determineCurrentLookupKey() {
        return DynamicDataSourceHolder.getDataSource();
    }

    public DataSource getMasterDataSource() {
        return masterDataSource;
    }

    public void setMasterDataSource(DataSource masterDataSource) {
        this.masterDataSource = masterDataSource;
    }

    //创建数据源
    private BasicDataSource createDataSource(String datasource) {

        // 查询所需信息
        DataSourceInfo dataSourceInfo = Const.DataSourceInfoMap.get(datasource);

        if (dataSourceInfo != null) {

            if ("Mysql".equals(dataSourceInfo.getDatabaseType())) {
                return createDataSource("com.mysql.jdbc.Driver", "jdbc:mysql://" + dataSourceInfo.getUrl() + "/" + dataSourceInfo.getDatabaseName(), dataSourceInfo.getUsername(), dataSourceInfo.getPassword());
            } else if ("SqlServer".equals(dataSourceInfo.getDatabaseType())) {

                return createDataSource("com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://" + dataSourceInfo.getUrl() + ";DatabaseName=" + dataSourceInfo.getDatabaseName(), dataSourceInfo.getUsername(), dataSourceInfo.getPassword());
            }

        }
        return null;
    }

    //创建数据源
    private BasicDataSource createDataSource(String driverClassName, String url,
                                             String username, String password) {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setTestWhileIdle(true);

        return dataSource;
    }

}
