package com.sikey.wa04.business.infrastructure.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@ConfigurationProperties("spring.datasource")
@Data
public class DatasourceConfig {
    private String url;
    private String username;
    private String password;
    private String driverClassName;
    private DruidDatasourceConfig druid;

    @Bean
    @Primary
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        try {

            datasource.setUrl(url);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);

            datasource.setInitialSize(druid.getInitialSize());
            datasource.setMinIdle(druid.getMinIdle());
            datasource.setMaxActive(druid.getMaxActive());
            datasource.setMaxWait(druid.getMaxWait());
            datasource.setTimeBetweenConnectErrorMillis(druid.getTimeBetweenEvictionRunsMillis());
            datasource.setMinEvictableIdleTimeMillis(druid.getMinEvictableIdleTimeMillis());
            datasource.setValidationQuery(druid.getValidationQuery());
            datasource.setTestWhileIdle(druid.getTestWhileIdle());
            datasource.setTestOnBorrow(druid.getTestOnBorrow());
            datasource.setTestOnReturn(druid.getTestOnReturn());
            datasource.setPoolPreparedStatements(druid.getPoolPreparedStatements());

            datasource.setMaxPoolPreparedStatementPerConnectionSize(druid.getMaxPoolPreparedStatementPerConnectionSize());
            // 这里会抛出 SQLException 异常
            datasource.setFilters(druid.getFilters());
            datasource.setConnectionProperties(druid.getConnectionProperties());

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return datasource;
    }
}
