package com.philisense.www.dynamic.druid.conf;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import org.springframework.util.StringUtils;


/**
 * druid 配置多数据源
 * 
 */
@Configuration
public class DynamicDruidDataSourceConfiguration {

    @Autowired
    private MybatisProperties properties;

    @Autowired
    private ObjectProvider<Interceptor[]> interceptorsProvider;

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private ObjectProvider<DatabaseIdProvider> databaseIdProvider;

    @Autowired
    private ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider;

	@Primary
    @Bean(name = "masterDataSource")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "slaveDataSource1")
    @ConfigurationProperties("spring.datasource.druid.slave1")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave1", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource1(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }
    
    @Bean(name = "slaveDataSource2")
    @ConfigurationProperties("spring.datasource.druid.slave2")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave2", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource2(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }
    
    @Bean(name = "slaveDataSource3")
    @ConfigurationProperties("spring.datasource.druid.slave3")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave3", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource3(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }
    @Bean(name = "slaveDataSource4")
    @ConfigurationProperties("spring.datasource.druid.slave4")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave4", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource4(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }
    @Bean(name = "dynamicDataSource")
    //@DependsOn({ "masterDataSource", "slaveDataSource1", "slaveDataSource2", "slaveDataSource3", "slaveDataSource4"})
    //@Primary
    public DynamicDataSource dataSource(
    		@Qualifier("masterDataSource") DataSource masterDataSource, 
    		@Autowired(required=false) @Qualifier("slaveDataSource1") DataSource slaveDataSource1, 
    		@Autowired(required=false) @Qualifier("slaveDataSource2") DataSource slaveDataSource2,
    		@Autowired(required=false) @Qualifier("slaveDataSource3") DataSource slaveDataSource3,
    		@Autowired(required=false) @Qualifier("slaveDataSource4") DataSource slaveDataSource4)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        if( null != masterDataSource ) targetDataSources.put(DynamicDruidDataSourceTypeEnum.MASTER, masterDataSource);
        if( null != slaveDataSource1 ) targetDataSources.put(DynamicDruidDataSourceTypeEnum.SLAVE1, slaveDataSource1);
        if( null != slaveDataSource2 ) targetDataSources.put(DynamicDruidDataSourceTypeEnum.SLAVE2, slaveDataSource2);
        if( null != slaveDataSource3 ) targetDataSources.put(DynamicDruidDataSourceTypeEnum.SLAVE3, slaveDataSource3);
        if( null != slaveDataSource4 ) targetDataSources.put(DynamicDruidDataSourceTypeEnum.SLAVE4, slaveDataSource4);
        
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
    
    @Bean
    public PlatformTransactionManager txManager(@Autowired @Qualifier("dynamicDataSource") DataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }
    
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;
    
    /*@Bean
    //@ConfigurationProperties(prefix = "mybatis.mapper-locations")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired @Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
        
        return sqlSessionFactoryBean;
    }*/

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired @Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        if (StringUtils.hasText(this.properties.getConfigLocation())) {
            sqlSessionFactoryBean.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        }
        applyConfiguration(sqlSessionFactoryBean);
        if (this.properties.getConfigurationProperties() != null) {
            sqlSessionFactoryBean.setConfigurationProperties(this.properties.getConfigurationProperties());
        }
        if (!ObjectUtils.isEmpty(this.interceptorsProvider.getIfAvailable())) {
            sqlSessionFactoryBean.setPlugins(this.interceptorsProvider.getIfAvailable());
        }
        if (this.databaseIdProvider.getIfAvailable() != null) {
            sqlSessionFactoryBean.setDatabaseIdProvider(this.databaseIdProvider.getIfAvailable());
        }
        if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
            sqlSessionFactoryBean.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        }
        if (this.properties.getTypeAliasesSuperType() != null) {
            sqlSessionFactoryBean.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
        }
        if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
            sqlSessionFactoryBean.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
        }
        if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
            sqlSessionFactoryBean.setMapperLocations(this.properties.resolveMapperLocations());
        }
        return sqlSessionFactoryBean;
    }

    private void applyConfiguration(SqlSessionFactoryBean factory) {
        org.apache.ibatis.session.Configuration configuration = this.properties.getConfiguration();
        if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
            configuration = new org.apache.ibatis.session.Configuration();
        }
        if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizersProvider.getIfAvailable())) {
            for (ConfigurationCustomizer customizer : this.configurationCustomizersProvider.getIfAvailable()) {
                customizer.customize(configuration);
            }
        }
        factory.setConfiguration(configuration);
    }
    
    /**
     * 去除监控页面底部的广告
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
    {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter()
        {
            @Override
            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
            {
            }
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException
            {
                chain.doFilter(request, response);
                // 重置缓冲区，响应头不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner, 除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }
            @Override
            public void destroy()
            {
            }
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}
