package com.dxhy.common.datasource.config;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.dxhy.common.config.DataConfig;
import com.dxhy.common.datasource.properties.DataSourceProperties;
import com.dxhy.common.datasource.properties.DynamicDataSourceProperties;

/**
 * 配置多数据源
 * 
 * @author jiaohongyang
 */
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig {
    @Resource
    private DynamicDataSourceProperties properties;

    private DataConfig dataConfig;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DynamicDataSource dynamicDataSource(DataSourceProperties dataSourceProperties) {
        this.dataConfig = dataSourceProperties.getDataConfig();

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(getDynamicDataSource(dataConfig.getDataBaseType()));

        // 默认数据源
        DruidDataSource defaultDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties,dataConfig.getDataBaseType());
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);

        return dynamicDataSource;
    }

    private Map<Object, Object> getDynamicDataSource(String dbType) {
        Map<String, DataSourceProperties> dataSourcePropertiesMap = properties.getDatasource();
        Map<Object, Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
        dataSourcePropertiesMap.forEach((k, v) -> {
            if (null == v.getDataConfig()) {
                v.setDataConfig(this.dataConfig);
            }
            DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v,dbType);
            targetDataSources.put(k, druidDataSource);
        });

        return targetDataSources;
    }

}