package org.apache.seatunnel.datasource.plugin.redis;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.ConnectionPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;

public class RedisClientService {
    public static Jedis connect(RedisConfiguration conf) {
        List<String> redisNodes = Collections.emptyList();
        switch (conf.getMode()) {
            case "SINGLE":
                Jedis jedis = new Jedis(conf.getHost(), conf.getPort());
                if (StringUtils.isNotBlank(conf.getAuth())) {
                    jedis.auth(conf.getAuth());
                }
                if (StringUtils.isNotBlank(conf.getUser())) {
                    jedis.aclSetUser(conf.getUser());
                }
                return jedis;
            case "CLUSTER":
                HashSet<HostAndPort> nodes = new HashSet<>();
                HostAndPort node = new HostAndPort(conf.getHost(), conf.getPort());
                nodes.add(node);
                if (!redisNodes.isEmpty()) {
                    for (String redisNode : redisNodes) {
                        String[] splits = redisNode.split(":");
                        if (splits.length != 2) {
                            throw new RuntimeException(
                                    "Invalid redis node information,"
                                            + "redis node information must like as the following: [host:port]");
                        }
                        HostAndPort hostAndPort =
                                new HostAndPort(splits[0], Integer.parseInt(splits[1]));
                        nodes.add(hostAndPort);
                    }
                }
                ConnectionPoolConfig connectionPoolConfig = new ConnectionPoolConfig();
                JedisCluster jedisCluster;
                if (StringUtils.isNotBlank(conf.getAuth())) {
                    jedisCluster =
                            new JedisCluster(
                                    nodes,
                                    JedisCluster.DEFAULT_TIMEOUT,
                                    JedisCluster.DEFAULT_TIMEOUT,
                                    JedisCluster.DEFAULT_MAX_ATTEMPTS,
                                    conf.getAuth(),
                                    connectionPoolConfig);
                } else {
                    jedisCluster = new JedisCluster(nodes);
                }
                return new JedisWrapper(jedisCluster);
            default:
                // do nothing
                throw new RuntimeException("Not support this redis mode");
        }
    }
}
