package ru.nbch.credit_tracker.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import ru.nbch.credit_tracker.config.settings.CreditTrackerSettings;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
@Configuration
@MapperScan(
        basePackages = "ru.nbch.credit_tracker.mapper.indic",
        sqlSessionFactoryRef = "sqlSessionIndic"
)
public class IndicDataSourceConfig extends DatabaseConfig {

    @Value("classpath:mybatis/mapper/indic/*.xml")
    private Resource[] resources;

    @Bean(name = "indicDataSource")
    public DataSource dataSource(CreditTrackerSettings config) throws SQLException {
        DataSource dataSource = createDataSource(config.getIndicDataSourceSettings());
        try (Connection connection = dataSource.getConnection()) {
            connection.isValid(3);
        } catch (SQLException e) {
            log.error("Unable to connect to Indic url={}", config.getIndicDataSourceSettings().url(), e);
            throw e;
        }
        log.info("Connected to Indic: url={}", config.getIndicDataSourceSettings().url());
        return dataSource;
    }

    @Bean(name = "sqlSessionIndic")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("indicDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setTypeHandlersPackage("ru.nbch.credit_tracker.config.datasource.handlers");
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "jdbcTemplateIndic")
    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(@Qualifier("indicDataSource") DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }
}

