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

@Configuration
@MapperScan(value = "kr.gmtc.gw.eyegw.db1", sqlSessionFactoryRef = "factory")
public class DataSourceConfigDB1 {
 
    @Primary
    @Bean(name = "datasource")
    @ConfigurationProperties(prefix = "database.db1.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Primary
    @Bean(name = "factory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        
        Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/DB1/*.xml");
        sqlSessionFactory.setMapperLocations(res);
        
        return sqlSessionFactory.getObject();
    }
    
    @Primary
	@Bean(name="SqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception{
		return new SqlSessionTemplate(sqlSessionFactory);
	}
    
    @Primary
	@Bean
	public DataSourceTransactionManager ATransactionManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
 		
}

