package com.webchat.service.listener;

import com.webchat.common.enums.ChatMessageTypeEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.controller.client.ChatWebSocket;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.domain.vo.response.mess.ChatMessageResponseVO;
import com.webchat.domain.vo.response.mess.PublicAccountArticleMessageVO;
import com.webchat.domain.vo.response.publicaccount.ArticleBaseResponseVO;
import com.webchat.service.FriendService;
import com.webchat.service.UserService;
import com.webchat.service.publicaccount.ArticleService;
import com.webchat.service.queue.dto.ArticleDelayConsumeMessageDTO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.WebSocket;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class RedisApplyMessageListener implements MessageListener {

    private final RedisTemplate redisTemplate;

    public RedisApplyMessageListener(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = (String) redisTemplate.getStringSerializer().deserialize(message.getChannel());
        String messageStr = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        log.info("redis message listener ======> channel:{}, message:{}", channel, messageStr);
        this.notifyApplyMessageByWebSession(messageStr);
    }


    private void notifyApplyMessageByWebSession(String receiver) {

        ChatWebSocket ws = ChatWebSocket.clients.get(receiver);
        if (ws == null) {
            return;
        }
        Session session = ws.getSession();
        if (session == null || !session.isOpen()) {
            return;
        }
        ChatMessageResponseVO chatMessageResponseVO = new ChatMessageResponseVO();
        chatMessageResponseVO.setType(ChatMessageTypeEnum.APPLY.getType());
        session.getAsyncRemote().sendText(JsonUtil.toJsonString(chatMessageResponseVO));
    }

}
