package com.wuban.tron.explore.dao.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author sky
 *
 */

@Configuration
@MapperScan(basePackages = "com.wuban.tron.explore.dao", sqlSessionTemplateRef = "sqlSessionTemplateEx")
public class DataSourceConfigEx {

    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    @Bean(name = "dataSourceEx")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource buildDataSource() {
        return DataSourceBuilder.create().type(this.dataSourceType).build();
    }

    @Bean(name = "sqlSessionFactoryEx")
    @Primary
    public SqlSessionFactory buildSqlSessionFactory(@Qualifier("dataSourceEx") final DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(
                new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mybatis-config.xml"));
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "transactionManagerEx")
    @Primary
    public DataSourceTransactionManager buildTransactionManager(
            @Qualifier("dataSourceEx") final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplateEx")
    @Primary
    public SqlSessionTemplate buildSqlSessionTemplate(
            @Qualifier("sqlSessionFactoryEx") final SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}