package com.ruoyi.framework.datasource;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.util.StringUtils;

/**
 * 动态数据源
 *
 * @author ruoyi
 */
public class DynamicDataSource extends AbstractRoutingDataSource
{

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
    {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

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

    // 存储所有目标数据源
    private Map<Object, Object> targetDataSources = new ConcurrentHashMap<>();
    @PostConstruct
    public void init() {
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.targetDataSources.putAll(targetDataSources);
    }

    /**
     * 动态添加数据源
     */
    public void addTargetDataSource(String dbKey, DataSource dataSource) throws NoSuchFieldException {
        if (StringUtils.isEmpty(dbKey) || dataSource == null) {
            throw new IllegalArgumentException("数据源标识和实例不能为空");
        }
        targetDataSources.put(dbKey, dataSource);


        super.afterPropertiesSet(); // 刷新配置
    }

    /**
     * 动态移除数据源
     */
    public void removeTargetDataSource(String dbKey) {
        if (StringUtils.isEmpty(dbKey)) {
            return;
        }
        targetDataSources.remove(dbKey);
        super.afterPropertiesSet(); // 刷新配置
    }

    public boolean containsDataSource(String dataSourceName) {
        return targetDataSources != null && targetDataSources.containsKey(dataSourceName);
    }

    public Set<String> getDataSourceNames() {
        if (targetDataSources != null) {
            return targetDataSources.keySet().stream()
                    .filter(key -> key instanceof String)
                    .map(key -> (String) key)
                    .collect(Collectors.toSet());
        }
        return new HashSet<>();
    }

}