package com.bsmlab.dfx.agent.config.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

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

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    private final Map<Object, Object> dataSourceMap = new ConcurrentHashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        return contextHolder.get();
    }

    public void setDataSource(String dataSourceName) {
        contextHolder.set(dataSourceName);
    }

    public void clearDataSource() {
        contextHolder.remove();
    }

    public Map<Object, Object> getDataSourceMap() {
        return this.dataSourceMap;
    }

    public void addDataSource(String dataSourceId, DataSource dataSource) {
        this.dataSourceMap.put(dataSourceId, dataSource);
        super.setTargetDataSources(this.dataSourceMap);
        super.afterPropertiesSet();
    }
}
