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.newdatasource"},
        sqlSessionTemplateRef = "newSqlSessionTemplate")
public class NewDataSourceConfig {

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

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

    @Bean("newSqlSessionFactory")
    public SqlSessionFactory hintSqlSessionFactory(
            @Value("${mybatis.new-data-source.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("newSqlSessionTemplate")
    public SqlSessionTemplate hintSqlSessionTemplate(@Qualifier("newSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }
}
