package com.tsi.monitoring.config;

import lombok.extern.slf4j.Slf4j;
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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;
import java.sql.SQLException;

@Configuration
@EnableTransactionManagement
@MapperScan(
        basePackages = "com.tsi.monitoring.mapper.section",
        sqlSessionFactoryRef = "sectionSqlSessionFactory"
)
@Slf4j
public class sectionDataSourceConfig {

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

    @Bean(name="sectionSqlSessionFactory")
    public SqlSessionFactory sectionSqlSessionFactory(@Qualifier("sectionDataSource") DataSource sectionDataSoruce,
                                                   ApplicationContext applicationContext) throws Exception, SQLException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(sectionDataSoruce);
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:mybatis/mapper/section/**.xml"));
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis/mybatis-config.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name="sectionSqlSessionTemplate")
    public SqlSessionTemplate managerSqlSessionTemplate(@Qualifier("sectionSqlSessionFactory") SqlSessionFactory sectionSqlSessionFactory) {
        return new SqlSessionTemplate(sectionSqlSessionFactory);
    }

    @Bean(name="sectionTransactionManager")
    public DataSourceTransactionManager adminTransactionManager(@Autowired @Qualifier("sectionDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
