package ru.yandex.webmaster3.storage.util.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

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

/**
 * Created by ifilippov5 on 19.01.17.
 */
public class JedisClusterFactory {
    private static final Logger log = LoggerFactory.getLogger(JedisClusterFactory.class);

    private static int MAX_IDLE = 1000;
    private static int MAX_TOTAL = 1000;
    private static int MAX_WAIT_MILLIS = 150000;
    private String nodes;

    public JedisCluster createCluster() {
        String[] listNodes = this.nodes.split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        for (String ip : listNodes) {
            try {
                String[] hostAndPort = ip.split(":");
                HostAndPort node = new HostAndPort(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
                nodes.add(node);
                log.warn("NODE: " + node.toString());
            } catch (Exception ex) {
                throw new RuntimeException("Invalid cluster node in properties file: " + ip, ex);
            }
        }
        JedisPoolConfig config = new JedisPoolConfig();
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setMaxIdle(MAX_IDLE);
        config.setMaxTotal(MAX_TOTAL);
        config.setBlockWhenExhausted(true);
        config.setMaxWaitMillis(MAX_WAIT_MILLIS);
        return new JedisCluster(nodes, config);
    }

    @Required
    public void setNodes(String nodes) {
        this.nodes = nodes;
    }
}
