package com.caliverse.admin.global.configuration;

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.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@MapperScan(value = "com.caliverse.admin.domain.dao.total", sqlSessionFactoryRef = "TotalSqlSessionFactory")
@EnableTransactionManagement
public class TotalMybatisConfig{
    @Value("${spring.mybatis.mapper-locations}")
    String mPath;

    @Bean(name = "totalDataSource")
    @ConfigurationProperties(prefix = "spring.total-datasource")
    public DataSource DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "TotalSqlSessionFactory")
    public SqlSessionFactory TotalSqlSessionFactory(@Qualifier("totalDataSource") DataSource DataSource, ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(DataSource);
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources(mPath));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "TotalSessionTemplate")
    public SqlSessionTemplate SqlSessionTemplate(@Qualifier("TotalSqlSessionFactory") SqlSessionFactory firstSqlSessionFactory) {
        return new SqlSessionTemplate(firstSqlSessionFactory);
    }

    @Bean(name = "totalTransactionManager")
    public DataSourceTransactionManager totalTransactionManager(@Qualifier("totalDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
