package com.nmgs.config;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.nmgs.entity.Consistant;
import com.nmgs.util.LogUtil;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Component
public class SubscribeListener implements MessageListener {
    /**
     * 当前websocket的session
     */
    private Session session;

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    /**
     * 取消订阅
     * @param key
     */
    private static RedisMessageListenerContainer redisMessageListenerContainer =
            SpringUtil.getBean(RedisMessageListenerContainer.class);
    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        String msg = null;
        try {
            msg = new String(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        if (msg.contains("\"")) {
            msg = msg.replace("\"", "");
        }
        if (ObjectUtil.isNotEmpty(session) && session.isOpen()) {
            try {
                if(msg.contains("unSubscribe")){
                    redisMessageListenerContainer.removeMessageListener(this);
                }else{
                    session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                LogUtil.WriteLog_Error("发送消息异常，msg = {"+msg+"} , e = {"+e.getMessage()+"}","SubscribeListener");
            }
        }
    }
}
