package com.scm.contract.config;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;

//import com.scm.contract.properties.DataSourceScmProperties;
import com.scm.contract.properties.DataSourceWzhtProperties;
import com.zaxxer.hikari.HikariDataSource;

/**
 * 多数据源配置。建议按此文件方式建立数据源。<br>
 * 注意本类开关的@EnableConfigurationProperties，一个数据源，对应一个DataSourcePorperties，
 * 如果还需要再多一个数据源，需要再创建一个DataSourceProperties，同样在本类开头配置，也配置相关的Bean.<br>
 * 在配置文件中参考同样的配置来配置更多的数据源。spring.ds1.datasource.hikari、spring.ds2.datasource.hikari  <br>
 * 网上有通过DataSourceBuilder.create().build()方式建立数据源的，但是不能保证数据测试正常，可能会有数据连接不释放的问题。<br>
 *
 * @author helikui
 *
 */
@Configuration
//@EnableConfigurationProperties(value = { DataSourceScmProperties.class,
//		DataSourceWzhtProperties.class })
@EnableConfigurationProperties(value = { DataSourceWzhtProperties.class })
public class DataSourceConfiguration {

//	@Bean("dataSource")
//	@ConfigurationProperties(prefix = "spring.datasource.scm.hikari")
//	@Primary
//	public HikariDataSource dataSource(DataSourceScmProperties properties) {
//		HikariDataSource dataSource = createDataSource(properties,
//				HikariDataSource.class);
//		if (StringUtils.hasText(properties.getName())) {
//			dataSource.setPoolName(properties.getName());
//		}
//		return dataSource;
//	}

	@Bean("dataSource2")
	@ConfigurationProperties(prefix = "spring.datasource.wzht.hikari")
	public HikariDataSource dataSource2(DataSourceWzhtProperties properties) {
		HikariDataSource dataSource = createDataSource(properties,
				HikariDataSource.class);
		if (StringUtils.hasText(properties.getName())) {
			dataSource.setPoolName(properties.getName());
		}
		return dataSource;
	}

//	@SuppressWarnings("unchecked")
//	protected static <T> T createDataSource(DataSourceScmProperties properties,
//			Class<? extends DataSource> type) {
//		return (T) properties.initializeDataSourceBuilder().type(type).build();
//	}

	@SuppressWarnings("unchecked")
	protected static <T> T createDataSource(DataSourceWzhtProperties properties,
			Class<? extends DataSource> type) {
		return (T) properties.initializeDataSourceBuilder().type(type).build();
	}

}
