package com.webchat.service.listener;

import com.webchat.common.util.JsonUtil;
import com.webchat.controller.client.VideoChatWebDcsSocket;
import com.webchat.domain.vo.request.mess.VideoChatMessageRequestVO;
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;
import java.io.IOException;

@Slf4j
@Component
public class RedisVideoOfferReceiveMessageListener implements MessageListener {

    private final RedisTemplate redisTemplate;

    public RedisVideoOfferReceiveMessageListener(@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 receiverId = chatMessage.getTargetUserId();
        // 校验用户ws 连接session是否在当前机器Hash表
        VideoChatWebDcsSocket ws = VideoChatWebDcsSocket.clients.get(receiverId);
        if (ws == null) {
            return;
        }
        Session session = ws.getSession();
        if (session == null || !session.isOpen()) {
            return;
        }
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
