package cn.ezhizao.framework.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态数据源
 *
 * @author ruoyi
 */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource
{
    private static Map<Object, Object> targetTargetDataSources = new ConcurrentHashMap<>();
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
    {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
        targetTargetDataSources = targetDataSources;
    }

    /**
     * 添加数据源
     * @param tenantId
     * @param dataSourceProperties
     */
    public void addDataSource(String tenantId, Map<String, Object> dataSourceProperties) {
        targetTargetDataSources.put(tenantId, dataSource(dataSourceProperties));
        super.setTargetDataSources(targetTargetDataSources);
        afterPropertiesSet();
    }

    /**
     * 判断是否存在数据源
     * @param tenantId
     * @return
     */
    public boolean existDataSource(String tenantId) {
        return targetTargetDataSources.containsKey(tenantId);
    }

    /**
     * 组装数据源
     * @param dataSourceProperties
     * @return
     */
    public DataSource dataSource(Map<String, Object> dataSourceProperties) {
        DataSource dataSource;
        try {
            dataSource = DruidDataSourceFactory.createDataSource(dataSourceProperties);
        } catch (Exception e) {
            log.error("dataSource: {}", e);
            throw new RuntimeException();
        }
        return dataSource;
    }

    @Override
    protected Object determineCurrentLookupKey()
    {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}
