package com.cool.store.datasource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p>
 * 动态数据源
 * </p>
 *
 * @author wangff
 * @since 2025/9/4
 */
@Component
@Primary
public class DynamicDataSource extends AbstractDataSource {

    @Autowired
    private DataSource defaultDataSource;

    @Autowired
    private DataSource platformDataSource;

    @Override
    public Connection getConnection() throws SQLException {
        DataSource currentDB = getCurrentDB();
        return currentDB.getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        DataSource currentDB = getCurrentDB();
        Connection connection = currentDB.getConnection(username, password);
        connection.setCatalog(DataSourceContextHolder.getDataSourceType());
        return connection;
    }

    protected DataSource getCurrentDB() {
        String dbName = DataSourceContextHolder.getDataSourceType();
        if (StringUtils.isBlank(dbName)) {
            return defaultDataSource;
        }
        return platformDataSource;
    }

}
