package com.webchat.service.listener;

import com.webchat.common.util.JsonUtil;
import com.webchat.controller.client.ChatWebSocket;
import com.webchat.domain.vo.request.mess.VideoChatMessageRequestVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.domain.vo.response.mess.ChatMessageResponseVO;
import com.webchat.service.UserService;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.Map;

@Slf4j
@Component
public class RedisGroupVideoOfferSendMessageListener implements MessageListener {


    @Autowired
    private UserService userService;

    private final RedisTemplate redisTemplate;

    public RedisGroupVideoOfferSendMessageListener(@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.handleGroupVideoChattingMessage(messageStr);
    }

    private void handleGroupVideoChattingMessage(String message) {

        VideoChatMessageRequestVO chatMessage = JsonUtil.fromJson(message, VideoChatMessageRequestVO.class);
        if (chatMessage == null) {
            return;
        }
        // 消息接受人，这里取得是群组id（代理人）
        String groupId = chatMessage.getTargetUserId();
        UserBaseResponseInfoVO group = userService.getUserBaseInfoByUserId(groupId);
        List<String> groupUserIds = userService.getGroupUserIdsFromCache(groupId);
        if (CollectionUtils.isEmpty(groupUserIds)) {
            return;
        }
        Map<String, ChatWebSocket> clients = ChatWebSocket.clients;
        for (String userId : groupUserIds) {
            if (userId.equals(chatMessage.getUserId())) {
                continue;
            }
            ChatWebSocket webSocket = clients.get(userId);
            if (webSocket == null) {
                continue;
            }
            Session session = webSocket.getSession();
            if (session != null && session.isOpen()) {
                // 给群聊下每个群成员推送视频邀请信息
                // 视频对话发送offer，这里走的是普通聊天，推送音视频请求给接收人
                ChatMessageResponseVO chatMessageResponseVO = new ChatMessageResponseVO();
                chatMessageResponseVO.setVideoOffer(true);
                chatMessageResponseVO.setSenderId(groupId);
                chatMessageResponseVO.setReceiverId(userId);
                chatMessageResponseVO.setSenderName(group.getUserName());
                String offerMessage = JsonUtil.toJsonString(chatMessageResponseVO);
                // 发送给接收人音视频通话申请实时通知
                session.getAsyncRemote().sendText(offerMessage);
            }
        }
    }
}
