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

import cn.reghao.tnb.content.app.config.DataSourceType;
import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * @author reghao
 * @date 2023-12-31 01:02:45
 */
//@Configuration
public class DynamicDataSourceConfig {
    //@Bean(name = "dynamicDataSource")
    public DynamicDataSource dynamicDataSource(DataSource dataSource) throws Exception {
        if (dataSource instanceof ShardingSphereDataSource) {
            ShardingSphereDataSource shardingDataSource = (ShardingSphereDataSource) dataSource;
            /*Map<String, DataSource> map = shardingDataSource.getDataSourceMap();
            DataSource dataSourceMaster = map.get(DataSourceType.master.getName());
            DataSource dataSourceSlave = map.get(DataSourceType.slave.getName());
            return getDynamicDataSource(dataSourceMaster, dataSourceSlave);*/
        }

        throw new Exception("DataSource is not ShardingDataSource");
    }

    private DynamicDataSource getDynamicDataSource(DataSource master, DataSource slave) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.master.getName(), master);
        targetDataSources.put(DataSourceType.slave.getName(), slave);
        return new DynamicDataSource(master, targetDataSources);
    }
}
