package cc.smtweb.framework.core.cache.redis;

import cc.smtweb.framework.core.util.JsonUtil;
import io.lettuce.core.RedisClient;
import io.lettuce.core.pubsub.RedisPubSubAdapter;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import org.springframework.context.ApplicationContext;

public class RedisSysTask {
    private ApplicationContext applicationContext;
    private StatefulRedisPubSubConnection<String, String> connection;
    private RedisClient redisClient;
    //订阅消息的channel，一般带通配符
    private String scribeChannel;
    //自己的唯一标记，自己发的消息不处理
    private String selfChannel;

    public RedisSysTask(ApplicationContext applicationContext, RedisClient redisClient, String scribeChannel, String selfChannel) {
        this.applicationContext = applicationContext;
        this.redisClient = redisClient;
        this.scribeChannel = scribeChannel;
        this.selfChannel = selfChannel;
    }

    public int run() {
        // 非集群模式下的发布订阅
        if (connection == null) {
            connection = redisClient.connectPubSub();

            if (connection != null) {
                connection.addListener(new RedisPubSubAdapter<String, String>() {
                    @Override
                    public void message(String channel, String message) {
                        if (channel.equalsIgnoreCase(selfChannel)) return;
                        RedisBroadcastEvent redisBroadcast = JsonUtil.parse(message, RedisBroadcastEvent.class);

                        applicationContext.publishEvent(redisBroadcast);
                    }
                });

                // 订阅
                RedisPubSubCommands<String, String> sync = connection.sync();
                sync.subscribe(scribeChannel);
            }
        }

        return 0;
    }

    public void close() {
        if (connection != null) {
            connection.close();
            connection = null;
        }
    }
}
