/**
 * 
 */
package org.springblade.etl.config;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.etl.properties.PreviewRedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

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

/**
 * @author wookvn
 *
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(PreviewRedisProperties.class)
public class JedisConfig {
	
	@Autowired
	private PreviewRedisProperties previewRedisProperties;

    //	@Bean("previewJedisCluster")
    public JedisCluster jedisPool(){
        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setMaxTotal(5);
        jedisPoolConfig.setTestWhileIdle(true);
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);

        if(CollectionUtil.isEmpty(previewRedisProperties.getNodes())){
            throw new ServiceException("PreviewRedis服务器节点必须要配置");
        }

        Set<HostAndPort> redisNodes = new HashSet<HostAndPort>();
        for(String node : previewRedisProperties.getNodes()) {
            redisNodes.add(HostAndPort.from(node));
        }

//        log.info("JedisPool连接成功:【{}:{}@{}】", host, previewRedisProperties.getPort(), previewRedisProperties.getDatabase());

        JedisCluster jedisCluster = new JedisCluster(redisNodes, previewRedisProperties.getTimeout(), previewRedisProperties.getTimeout(), previewRedisProperties.getMaxAttempts(), previewRedisProperties.getPassword(), jedisPoolConfig);

        log.info("PreviewJedisCluster连接成功");

        return jedisCluster;

//        String host = previewRedisProperties.getNodes().get(0);
//        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host,
//        		previewRedisProperties.getPort(), 2000, previewRedisProperties.getPassword(), previewRedisProperties.getDatabase());
//        log.info("JedisPool连接成功:【{}:{}@{}】", host, previewRedisProperties.getPort(), previewRedisProperties.getDatabase());
//        return jedisPool;
    }
}