package com.ibeetl.admin.core.conf;

import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.UnderlinedNameConversion;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;


@Configuration
public class DataSourceConfig {
	@Bean(name = "dataSource")
	@Primary
	public DataSource datasource(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
		ds.setUsername(env.getProperty("spring.datasource.username"));
		ds.setPassword(env.getProperty("spring.datasource.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		ds.setMaxLifetime(Long.parseLong(env.getProperty("spring.datasource.hikari.max-lifetime")));
		ds.setConnectionTimeout(Long.parseLong(env.getProperty("spring.datasource.hikari.connection-timeout")));
		ds.setMinimumIdle(Integer.parseInt(env.getProperty("spring.datasource.hikari.minimum-idle")));
		ds.setMaximumPoolSize(Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")));
		ds.setAutoCommit(Boolean.parseBoolean(env.getProperty("spring.datasource.hikari.auto-commit")));
		ds.setConnectionTestQuery(env.getProperty("spring.datasource.hikari.connection-test-query"));
		ds.setIdleTimeout(Integer.parseInt(env.getProperty("spring.datasource.hikari.idle-timeout")));
		ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
		return ds;
	}

	@Bean(name = "datas")
	@Primary
	public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("dataSource")DataSource master){
		SqlManagerFactoryBean factoryBean=new SqlManagerFactoryBean();
		BeetlSqlDataSource source=new BeetlSqlDataSource();
		source.setMasterSource(master);
		factoryBean.setCs(source);
		factoryBean.setDbStyle(new MySqlStyle());
		//开启驼峰
		factoryBean.setNc(new UnderlinedNameConversion());
		//sql文件路径
//		factoryBean.setSqlLoader(new ClasspathLoader("/sql"));
		return factoryBean;
	}


}



