package quant.rich.emoney.config;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

@Configuration
@MapperScan(basePackages = "quant.rich.emoney.mapper.postgre", sqlSessionTemplateRef = "postgreSqlSessionTemplate")
public class PostgreMybatisConfig {
    
    public static final String POSTGRE_TRANSACTION_MANAGER = "postgreTransactionManager";
    
    @Value("${mybatis-plus.mapper-locations}")
    private String[] mapperLocations;
    
    @Bean("postgreSqlSessionFactory")
    public SqlSessionFactory postgreSqlSessionFactory(
        @Qualifier("postgreDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        
        
        List<Resource> resources = new ArrayList<>();
        for (String mapperLocation : mapperLocations) {
            for (Resource resource : new PathMatchingResourcePatternResolver()
                    .getResources(mapperLocation)) {
                resources.add(resource);
            }
        }
        factory.setMapperLocations(
            resources.toArray(new Resource[0])
        );
        
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        factory.setPlugins(interceptor);
        
        return factory.getObject();
        
    }
    
    @Bean("postgreSqlSessionTemplate")
    public SqlSessionTemplate sqliteSqlSessionTemplate(@Qualifier("postgreSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
    @Bean(POSTGRE_TRANSACTION_MANAGER)
    public DataSourceTransactionManager postgreTransacetionManager(@Qualifier("postgreDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
