package ru.nbch.indicsearchservice.config.datasource;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import ru.nbch.indicsearchservice.util.DataSourceUpdater;

@Configuration
public class IndicDataSourceConfig {
    private static final Logger log = LoggerFactory.getLogger(IndicDataSourceConfig.class);

    private final DataSourceUpdater dataSourceUpdater;

    public IndicDataSourceConfig(DataSourceUpdater dataSourceUpdater) {
        this.dataSourceUpdater = dataSourceUpdater;
    }

    @Bean(name = "indicDataSource")
    public DataSource indicDataSource() {
        log.info("Connecting to indic datasource...");
        return dataSourceUpdater.getDataSource(DataSourceUpdater.DataSourceType.INDIC);
    }

    @Bean(name = "indicSqlSessionFactoryBean")
    public SqlSessionFactory sqlSessionFactoryBean() {
        return dataSourceUpdater.getSqlSessionFactory(DataSourceUpdater.DataSourceType.INDIC);
    }

    @Bean(name = "indicTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("indicDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
