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.hint"},
        sqlSessionTemplateRef = "hintSqlSessionTemplate")
public class HintDataSourceConfig {

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

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

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

    @Bean("hintSqlSessionTemplate")
    public SqlSessionTemplate hintSqlSessionTemplate(@Qualifier("hintSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }
}
