package com.webchat.service.listener;

import com.webchat.common.util.JsonUtil;
import com.webchat.controller.client.GroupVideoChatWebSocket;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class RedisGroupVideoOnlineMessageListener implements MessageListener {


    @Autowired
    private UserService userService;

    private final RedisTemplate redisTemplate;

    public RedisGroupVideoOnlineMessageListener(@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) {
        GroupVideoChatWebSocket.VideoCustomMessage videoCustomMessage =
                JsonUtil.fromJson(message, GroupVideoChatWebSocket.VideoCustomMessage.class);
        if (videoCustomMessage == null) {
            return;
        }
        String groupId = videoCustomMessage.getGroupId();
        List<String> groupUserIds = userService.getGroupUserIdsFromCache(groupId);
        if (CollectionUtils.isEmpty(groupUserIds)) {
            return;
        }
        Set<String> onlineUserIds = videoCustomMessage.getUserIds();
        Map<String, UserBaseResponseInfoVO> onlineUserMap = userService.batchGetUserInfoFromCache(new ArrayList<>(onlineUserIds));
        videoCustomMessage.setOnlineUserMap(onlineUserMap);
        Map<String, GroupVideoChatWebSocket> clients = GroupVideoChatWebSocket.clients.get(groupId);
        if (MapUtils.isEmpty(clients)) {
            return;
        }
        for (String userId : groupUserIds) {
            GroupVideoChatWebSocket webSocket = clients.get(userId);
            if (webSocket == null) {
                continue;
            }
            Session session = webSocket.getSession();
            if (session != null && session.isOpen()) {
                // 给群聊下每个群成员推送视频邀请信息
                // 视频对话发送offer，这里走的是普通聊天，推送音视频请求给接收人
                // 发送给接收人音视频通话申请实时通知
                try {
                    session.getBasicRemote().sendText(JsonUtil.toJsonString(videoCustomMessage));
                } catch (IOException e) {
                    log.error("群聊多人音视频通话用户上线消息推送失败 =====> ", e);
                }
            }
        }
    }
}
