package com.scpyun.base.core.config;

import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.properties.PublicProperties;
import com.scpyun.base.core.utils.Global;
import com.scpyun.base.core.utils.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;

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

/**
 * redis工具类
 * @author eclair
 *
 */
@Configuration
public class JedisPoolConfig {

	@Autowired
	public PublicProperties publicProperties;
	
	@Bean
	public JedisPool jedisPool() {
		if(StringUtils.isEmpty(Global.getConfig("scp.redis.host"))){
			return null;
		}
		final redis.clients.jedis.JedisPoolConfig jedisPoolConfig = new redis.clients.jedis.JedisPoolConfig();
		jedisPoolConfig.setMaxIdle(publicProperties.getRedisMaxIdle());
		jedisPoolConfig.setMaxTotal(publicProperties.getRedisMaxTotal());
		jedisPoolConfig.setTestOnBorrow(true);
		final JedisPool jedisPool = new JedisPool(
				jedisPoolConfig,
                publicProperties.getRedisHost(),
                publicProperties.getRedisPort(),
                publicProperties.getRedisTimeout(),
                publicProperties.getRedisPassword(), 0);
		return jedisPool;
	}

	/**
	 * need config
	 * scp.redis.sentinel.master.name=mymaster
	 * scp.redis.sentinel.host=10.40.20.2_3679,10.40.20.3_33679
	 * @return
	 */
	@Bean
	public JedisSentinelPool jedisSentinelPool() {
		if(StringUtils.isEmpty(Global.getConfig("scp.redis.sentinel.host"))){
			return null;
		}
		if (StringUtils.isEmpty(Global.getConfig("scp.redis.sentinel.master.name"))) {
			throw new CustomException("config --> [scp.redis.sentinel.master.name] ?");
		}
		String sentinelMasterName = Global.getConfig("scp.redis.sentinel.master.name");
		Set<String> sentinels = new HashSet<String>();
		try {
			String[] sentinelHostSplice = Global.getConfig("scp.redis.sentinel.host").split(",");
			for (String s : sentinelHostSplice) {
				sentinels.add(s.split("_")[0] + ":" + s.split("_")[1]);
			}
		} catch (Exception e) {
			throw new CustomException("config --> [scp.redis.sentinel.host] 格式不正确！ 例: =_3679,10.40.20.3_33679");
		}

		GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
		genericObjectPoolConfig.setMaxIdle(publicProperties.getRedisMaxIdle());
		genericObjectPoolConfig.setMaxTotal(publicProperties.getRedisMaxTotal());
		genericObjectPoolConfig.setTestOnBorrow(true);
		final JedisSentinelPool jedisSentinelPoolConfig = new JedisSentinelPool(
				sentinelMasterName,
				sentinels,
				genericObjectPoolConfig,
				publicProperties.getRedisTimeout(),
				publicProperties.getRedisSentinelPassword());
		return jedisSentinelPoolConfig;
	}

}
