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.datasource1", sqlSessionFactoryRef = "factory")
public class DataSourceConfigDB1 {
 
    @Bean(name = "datasource")
    @ConfigurationProperties(prefix = "database.db1.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean(name = "factory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setCallSettersOnNulls(true);

        Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml");
        sqlSessionFactory.setMapperLocations(res);

        sqlSessionFactory.setConfiguration(config);
        
        return sqlSessionFactory.getObject();
    }
    
	@Bean(name="SqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(@Qualifier("factory") SqlSessionFactory sqlSessionFactory) throws Exception{
		return new SqlSessionTemplate(sqlSessionFactory);
	}
    
	@Bean
	public DataSourceTransactionManager ATransactionManager(@Qualifier("datasource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
 		
}