package com.zm.order.tool.server.config;

import com.zm.order.tool.server.utils.IoUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.InputStream;


/**
 * @Description Hint数据源配置
 * @Author: ph
 * @Date: 2019/12/5 15:30
 */
@Configuration
@MapperScan(basePackages = {"com.zm.order.tool.server.history"},
        sqlSessionTemplateRef = "historySqlSessionTemplate")
public class HistoryDataSourceConfig {

    private static final Logger logger = LoggerFactory.getLogger(HistoryDataSourceConfig.class);

    @Bean(name = "historyDataSource")
    public DataSource historyDataSource() throws Exception {
        InputStream inputStream = new ClassPathResource("sharding-history-data.yml").getInputStream();
        DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(IoUtils.toBytes(inputStream));
        logger.info("init history data source success");
        return dataSource;
    }

    @Bean("historySqlSessionFactory")
    public SqlSessionFactory hintSqlSessionFactory(
            @Value("${mybatis.history.data.mapper-locations}") String mapperLocations,
            @Value("${mybatis.config-location}") String configLocation
    ) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(historyDataSource());
        Resource[] mapperLocationsResource = new PathMatchingResourcePatternResolver().getResources(mapperLocations);
        sqlSessionFactoryBean.setMapperLocations(mapperLocationsResource);
        sqlSessionFactoryBean.setConfigLocation(
                new PathMatchingResourcePatternResolver().getResource(configLocation)
        );
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("historySqlSessionTemplate")
    public SqlSessionTemplate hintSqlSessionTemplate(@Qualifier("historySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
