package cn.myapps.conf;


import javax.annotation.PreDestroy;
import javax.sql.DataSource;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import com.alibaba.druid.pool.DruidDataSource;
import com.bcxin.saas.core.logs.Logging;
import com.bcxin.saas.core.logs.SysLogProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/**
 * Created by arnold.zhu on 6/13/2017.
 */
@Configuration
public class DataSourceConfig implements TransactionManagementConfigurer {
	@Value("${spring.datasource.url}")
	private String dbUrl;

	@Value("${spring.datasource.username}")
	private String username;

	@Value("${spring.datasource.password}")
	private String password;

	@Value("${spring.datasource.driver-class-name}")
	private String driverClassName;

	@Value("${spring.datasource.initialSize}")
	private int initialSize;

	@Value("${spring.datasource.maxActive}")
	private int maxActive;

	@Value("${spring.datasource.maxWait}")
	private int maxWait;

	@Value("${spring.datasource.validationQuery}")
	private String validationQuery;

	@Value("${spring.datasource.testWhileIdle}")
	private boolean testWhileIdle;

	@Value("${spring.datasource.testOnBorrow}")
	private boolean testOnBorrow;

	@Value("${spring.datasource.testOnReturn}")
	private boolean testOnReturn;

	@Logging
	@Bean({"druidDataSource","loggerDataSource"})
	public DataSource druidDataSource() {
		if (maxWait < 100) {
			maxWait = 3600;
		}


		DataSource dataSource = null;
		try {
			dataSource = PersistenceUtils.getDruidDataSource("CORE",
					username, password, driverClassName, dbUrl, String.valueOf(maxActive),
					String.valueOf(maxWait));
			SysLogProvider.setDataSource(dataSource);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dataSource;
	}

	@Bean
	public JdbcTemplate jdbcTemplate(DataSource kmDataSource) {
		return new JdbcTemplate(kmDataSource);

	}

	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(druidDataSource());
	}

	@PreDestroy
	public void preDestroy() throws InterruptedException {
		DataSource dataSource =druidDataSource();
		if (dataSource != null && dataSource instanceof DruidDataSource) {
			DruidDataSource dds = (DruidDataSource) dataSource;
			dds.clearFilters();
			dds.unregisterMbean();
			dds.close();
		}
	}
}