package kr.gmtc.gw.eyegw.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.eyegw.db2", sqlSessionFactoryRef = "factory2")
public class DataSourceConfigDB2 {
 
    @Bean(name = "datasource2")
    @ConfigurationProperties(prefix = "database.db2.datasource")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean(name = "factory2")
    public SqlSessionFactory sqlSessionFactory2(@Qualifier("datasource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        
        Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/DB2/*.xml");
        sqlSessionFactory.setMapperLocations(res);
		
        return sqlSessionFactory.getObject();
    }
    
    @Bean(name="SqlSessionTemplate2")
	public SqlSessionTemplate sqlSessionTemplate2(SqlSessionFactory sqlSessionFactory) throws Exception{
		return new SqlSessionTemplate(sqlSessionFactory);
	}
    
 // DataSource 에서 Transaction 관리를 위한 Manager 클래스 등록
 	@Bean
 	public DataSourceTransactionManager BTransactionManager(@Qualifier("datasource2") DataSource dataSource) {
 		return new DataSourceTransactionManager(dataSource);
 	}
}

