package com.webchat.controller.client;

import com.webchat.common.enums.RedisMessageChannelTopicEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.common.util.SpringContextUtil;
import com.webchat.domain.vo.request.mess.VideoChatMessageRequestVO;
import com.webchat.service.listener.RedisMessageSender;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.*;

@Api(tags = "【音视频】分布式一对一信令服务")
@Data
@Slf4j
@Component
@ServerEndpoint(value = "/ws/video-chat/dcs/{userId}")
public class VideoChatWebDcsSocket {

    //存储客户端的连接对象,每个客户端连接都会产生一个连接对象
    public static ConcurrentHashMap<String, VideoChatWebDcsSocket> clients = new ConcurrentHashMap();

    //每个连接都会有自己的会话
    private Session session;

    private String userId;

    @OnOpen
    public void open(@PathParam("userId") String userId, Session session, EndpointConfig config){

        log.info("音视频通话用户{}的客户端连接成功！", userId);
        clients.put(userId, this);
        this.session = session;
        this.userId = userId;
    }

    @OnClose
    public void close(){
        clients.remove(userId);
    }

    @OnError
    public void error(Throwable error){
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到来自用户{}的消息:{}", userId, message);
        VideoChatMessageRequestVO chatMessage = JsonUtil.fromJson(message, VideoChatMessageRequestVO.class);
        if (chatMessage == null) {
            return;
        }
        RedisMessageSender redisMessageSender = SpringContextUtil.getBean(RedisMessageSender.class);
        if (chatMessage.getType().equals("offer")) {
            // 发送通过邀请提醒消息
            // 支持分布式场景，走广播模式
            redisMessageSender.sendMessage(RedisMessageChannelTopicEnum.VIDEO_OFFER_SEND.getChannel(), message);
            // 发送对话数据
            redisMessageSender.sendMessage(RedisMessageChannelTopicEnum.VIDEO_OFFER_RECEIVER.getChannel(), message);
            return;
        }
        // 发送对话数据
        redisMessageSender.sendMessage(RedisMessageChannelTopicEnum.VIDEO_OFFER_RECEIVER.getChannel(), message);
    }
}

