package com.tsi.monitoring.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionException;
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.utis",
        sqlSessionFactoryRef = "utisSqlSessionFactory"
)
@Slf4j
public class utisDataSourceConfig {
    @Bean(name="utisDataSource")
    @ConfigurationProperties(prefix = "spring.utis-datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

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

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

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

