package com.tzld.piaoquan.api.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = "com.tzld.piaoquan.api.dao.mapper", sqlSessionFactoryRef = "growthSqlSessionFactory")
@MapperScan(basePackages = "com.tzld.piaoquan.growth.common.dao.mapper", sqlSessionFactoryRef = "growthSqlSessionFactory")
public class DataSourceConfig {
    static final String MAPPER_LOCATION_MASTER = "classpath*:mapper/**/*.xml";

    @Bean(name = "dataSource")
    @ConfigurationProperties("spring.datasource")
    public DataSource getDataSource(){
        return new DruidDataSource();
    }

    @Primary
    @Bean(name = "growthTransactionManager")
    public PlatformTransactionManager growthTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "growthSqlSessionFactory")
    public SqlSessionFactory growthSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(DataSourceConfig.MAPPER_LOCATION_MASTER));
        sessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        sessionFactoryBean.getObject().getConfiguration().setUseGeneratedKeys(true);
        return sessionFactoryBean.getObject();
    }

}