package com.pcloud.book.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
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.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * clickhouse 数据源配置
 */
@Slf4j
@Configuration
@MapperScan(basePackages = "com.pcloud.book.mapper.clickhouse", sqlSessionFactoryRef = "clickHouseSqlSessionFactory")
public class CHDataSource {

    @Bean(name = "clickHouseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource-ch")
    public DataSource druidDataSource() {
        log.info("[初始化clickhouse数据源 - druidDataSource]");
        return new DruidDataSource();
    }


    @Bean("clickHouseSqlSessionFactory")
    public SqlSessionFactory clickHouseSqlSessionFactory(@Qualifier("clickHouseDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/clickhouse/**/*Mapper.xml"));
        log.info("[初始化clickhouse数据源 - clickHouseSqlSessionFactory]");
        return bean.getObject();
    }

    @Bean("clickHouseSqlSessionTemplate")
    public SqlSessionTemplate clickHouseSqlSessionTemplate(
            @Qualifier("clickHouseSqlSessionFactory") SqlSessionFactory sessionFactory) {
        log.info("[初始化clickhouse数据源 - clickHouseSqlSessionTemplate]");
        return new SqlSessionTemplate(sessionFactory);
    }

}
