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.hintnew"},
        sqlSessionTemplateRef = "newHintSqlSessionTemplate")
public class NewHintDataSourceConfig {

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

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

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

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