package org.atmospheregames.network.redis;

import com.google.gson.JsonObject;
import lombok.Getter;
import org.atmospheregames.network.Network;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisClient {

    private static final String CHANNEL = "NETWORK";
    @Getter private final RedisListener redisListener;
    private final JedisPool jedisPool;

    public RedisClient(Network plugin) {
        this.jedisPool = new JedisPool(plugin.getConfig().getString("REDIS.HOST"), plugin.getConfig().getInt("REDIS.PORT"));
        this.redisListener = new RedisListener();

        Jedis jedis = jedisPool.getResource();

        //jedis.auth

        new Thread(() -> jedis.subscribe(redisListener, CHANNEL)).start();
        System.out.println("[Redis] Connected to redis successfully.");
    }

    public void destroy() {
        jedisPool.destroy();
    }

    public void write(JsonObject json) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.publish(CHANNEL, json.toString());
        }
    }
}
