package com.blueland.ebpm.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

/**
 * @description 数据源配置
 * @author lw
 */
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DefaultDatasource {

	/**
	 * @description 定义数据源
	 * @author lw
	 * @param env 环境变量
	 * @updateTime 2021/5/13
	 */
	@Bean(name = "datasource")
	public DataSource datasource(Environment env) throws NumberFormatException {
		if (log.isDebugEnabled()) {
			log.debug("spring.datasource.url=" + env.getProperty("spring.datasource.url"));
		}
		HikariConfig hikariConfig = new HikariConfig();
		hikariConfig.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		hikariConfig.setJdbcUrl(env.getProperty("spring.datasource.url"));
		hikariConfig.setConnectionTestQuery(env.getProperty("spring.datasource.hikari.connection-test-query"));
		hikariConfig.setPoolName("springHikariCP");
		hikariConfig.setUsername(env.getProperty("spring.datasource.username"));
		hikariConfig.setPassword(env.getProperty("spring.datasource.password"));
		String connectionTimeout = env.getProperty("spring.datasource.hikari.connection-timeout");
		if (connectionTimeout != null) {
			hikariConfig.setConnectionTimeout(Long.parseLong(connectionTimeout));
		}
		String idleTimeout = env.getProperty("spring.datasource.hikari.idle-timeout");
		if (idleTimeout != null) {
			hikariConfig.setIdleTimeout(Long.parseLong(idleTimeout));
		}
		String validationTimeout = env.getProperty("spring.datasource.hikari.validation-timeout");
		if (validationTimeout != null) {
			hikariConfig.setValidationTimeout(Long.parseLong(validationTimeout));
		}
		String maxLifetime = env.getProperty("spring.datasource.hikari.max-lifetime");
		if (maxLifetime != null) {
			hikariConfig.setMaxLifetime(Long.parseLong(maxLifetime));
		}
		String maximumPoolSize = env.getProperty("spring.datasource.hikari.maximum-pool-size");
		if (maximumPoolSize != null) {
			hikariConfig.setMaximumPoolSize(Integer.parseInt(maximumPoolSize));
		}

		return new HikariDataSource(hikariConfig);
	}
}
