package cn.reghao.tnb.content.app.config.mybatis;

import cn.reghao.tnb.content.app.config.DataSourceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

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

/**
 * @author reghao
 * @date 2023-12-30 22:32:40
 */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
    public static final ThreadLocal<String> name = new ThreadLocal<>();

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

    @Override
    protected Object determineCurrentLookupKey() {
        String type = name.get();
        if (type == null) {
            type = DataSourceType.master.getName();
        }

        //log.info("use DataSource -> {}", type);
        return type;
    }
}
