package cn.quantgroup.xyqb.config.data;

import cn.quantgroup.xyqb.session.XyqbSessionContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Miraculous on 15/7/4.
 */
@Configuration
public class RedisConfig {

    @Value("${xyqb.redis.defaultExpiration}")
    private Long defaultExpiration;
    @Value("${xyqb.redis.master.host}")
    private String masterHost;
    @Value("${xyqb.redis.master.port}")
    private int masterPort;
    @Value("${xyqb.redis.master.name}")
    private String masterName;
    @Value("${xyqb.redis.sentinel1.host}")
    private String sentinel1Host;
    @Value("${xyqb.redis.sentinel1.port}")
    private int sentinel1port;
    @Value("${xyqb.redis.sentinel2.host}")
    private String sentinel2Host;
    @Value("${xyqb.redis.sentinel2.port}")
    private int sentinel2port;
    @Value("${xyqb.redis.sentinel3.host}")
    private String sentinel3Host;
    @Value("${xyqb.redis.sentinel3.port}")
    private int sentinel3port;
    @Value("${xyqb.redis.master.password}")
    private String passWord;

    private RedisConnectionFactory generateDevConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(masterHost);
        factory.setPort(masterPort);
        factory.setPassword(passWord);
        factory.setUsePool(true);
        factory.setConvertPipelineAndTxResults(true);
        JedisPoolConfig poolConfig = generatePoolConfig();
        factory.setPoolConfig(poolConfig);
        factory.afterPropertiesSet();
        return factory;
    }

    private RedisConnectionFactory generateReleaseConnectionFactory() {
        RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration();
        RedisNode master = new RedisNode(masterHost, masterPort);
        master.setName(masterName);
        Set<RedisNode> sentinels = new HashSet<>();
        RedisNode sentinel1 = new RedisNode(sentinel1Host, sentinel1port);
        RedisNode sentinel2 = new RedisNode(sentinel2Host, sentinel2port);
        RedisNode sentinel3 = new RedisNode(sentinel3Host, sentinel3port);
        sentinels.add(sentinel1);
        sentinels.add(sentinel2);
        sentinels.add(sentinel3);
        sentinelConfiguration.setMaster(master);
        sentinelConfiguration.setSentinels(sentinels);
        JedisPoolConfig poolConfig = generatePoolConfig();
        JedisConnectionFactory factory = new JedisConnectionFactory(sentinelConfiguration, poolConfig);
        factory.setHostName(masterHost);
        factory.setPort(masterPort);
        factory.setTimeout(5000);
        factory.setUsePool(true);
        factory.setConvertPipelineAndTxResults(true);
        factory.afterPropertiesSet();
        return factory;
    }

    private JedisPoolConfig generatePoolConfig() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(20);
        poolConfig.setMaxTotal(300);
        poolConfig.setMaxWaitMillis(5000);
        poolConfig.setTestOnBorrow(true);
        return poolConfig;
    }

    @Bean(name = "redisConnectionFactory")
    RedisConnectionFactory factory() {
        if (StringUtils.isEmpty(masterName)) {
            return generateDevConnectionFactory();
        } else {
            return generateReleaseConnectionFactory();
        }
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory factory) {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        template.setEnableTransactionSupport(false);
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jdkSerializationRedisSerializer);
        template.setDefaultSerializer(jdkSerializationRedisSerializer);
        template.setConnectionFactory(factory);

        XyqbSessionContextHolder.setRedisTemplate(stringRedisTemplate(factory));
        return template;
    }

    @Bean(name = "stringRedisTemplate")
    public RedisTemplate<String, String> stringRedisTemplate(
            RedisConnectionFactory factory) {
        final RedisTemplate<String, String> template = new RedisTemplate<>();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        template.setEnableTransactionSupport(false);
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jdkSerializationRedisSerializer);
        template.setDefaultSerializer(jdkSerializationRedisSerializer);
        template.setConnectionFactory(factory);
        return template;
    }

    @Bean(name = "cacheManager")
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(defaultExpiration);
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }
}
