package com.webchat.service.listener;

import com.webchat.common.util.JsonUtil;
import com.webchat.common.util.SpringContextUtil;
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.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;

@Slf4j
@Component
public class RedisVideoOfferSendMessageListener implements MessageListener {

    private final RedisTemplate redisTemplate;

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

    /**
     * 发送音视频通话邀请
     *
     * @param message
     */
    private void handleVideoChattingMessage(String message) {
        VideoChatMessageRequestVO chatMessage = JsonUtil.fromJson(message, VideoChatMessageRequestVO.class);
        if (chatMessage == null) {
            return;
        }
        String sendUserId = chatMessage.getUserId();
        String receiverId = chatMessage.getTargetUserId();
        // 校验用户ws 连接session是否在当前机器Hash表
        ChatWebSocket ws = ChatWebSocket.clients.get(receiverId);
        if (ws == null) {
            return;
        }
        Session session = ws.getSession();
        if (session == null || !session.isOpen()) {
            return;
        }
        // 校验用户身份信息
        UserService userService = SpringContextUtil.getBean(UserService.class);
        UserBaseResponseInfoVO sender = userService.getUserInfoByUserId(sendUserId);
        UserBaseResponseInfoVO receiver = userService.getUserInfoByUserId(receiverId);
        if (sender.getRoleCode() > 2 || receiver.getRoleCode() > 2) {
            // 音视频当前仅支持普通用户之间对话
            return;
        }
        // 视频对话发送offer，这里走的是普通聊天，推送音视频请求给接收人
        ChatMessageResponseVO chatMessageResponseVO = new ChatMessageResponseVO();
        chatMessageResponseVO.setVideoOffer(true);
        chatMessageResponseVO.setSenderId(sendUserId);
        chatMessageResponseVO.setReceiverId(receiverId);
        chatMessageResponseVO.setSenderName(sender.getUserName());
        String offerMessage = JsonUtil.toJsonString(chatMessageResponseVO);
        // 发送给接收人音视频通话申请实时通知
        session.getAsyncRemote().sendText(offerMessage);
    }
}
