package kr.gmtc.gw.standstatus.database.config;

import javax.sql.DataSource;

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.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.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(value = "kr.gmtc.gw.standstatus.database.datasource2", sqlSessionFactoryRef = "factory_db2")
public class DataSourceConfigDB2 {
 
    @Bean(name = "datasource2")
    @ConfigurationProperties(prefix = "database.db2.datasource")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean(name = "factory_db2")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource2") DataSource dataSource2) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource2);

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setCallSettersOnNulls(true);
        
        Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml");
        sqlSessionFactory.setMapperLocations(res);
        
        sqlSessionFactory.setConfiguration(config);
        
        return sqlSessionFactory.getObject();
    }
    
	@Bean(name="SqlSessionTemplate_db2")
	public SqlSessionTemplate sqlSessionTemplate(@Qualifier("factory_db2") SqlSessionFactory sqlSessionFactory) throws Exception{
		return new SqlSessionTemplate(sqlSessionFactory);
	}
    
	@Bean
	public DataSourceTransactionManager BTransactionManager(@Qualifier("datasource2") DataSource dataSource2) {
		return new DataSourceTransactionManager(dataSource2);
	}
 		
}