package com.changhu.support.ws.server;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson2.TypeReference;
import com.changhu.support.ws.enums.WsMsgType;
import com.changhu.support.ws.handler.BaseMessageHandler;
import com.changhu.support.ws.interceptor.WsAuthenticationInterceptor;
import com.changhu.support.ws.manager.UserConnectWebsocketManager;
import com.changhu.support.ws.pojo.dto.WsMsgDTO;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * author: luozhun
 * desc: 后台管理用户连接websocket
 * createTime: 2023/8/28 9:12
 */
@Slf4j
@Component
public class ManagementWebSocketServer extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(@NotNull WebSocketSession session) {
        Long userId = (Long) session.getAttributes().get(WsAuthenticationInterceptor.attributeName);
        if (userId != null) {
            //删除老的连接 建立新的链接
            UserConnectWebsocketManager.removeAndClose(userId);
            UserConnectWebsocketManager.add(userId, session);
        }
    }

    @Override
    public void handleTextMessage(@NotNull WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        WsMsgDTO<String> testSocketDTO = new TypeReference<WsMsgDTO<String>>() {
        }.parseObject(payload);

        WsMsgType msgType = testSocketDTO.getMsgType();
        BaseMessageHandler baseMessageHandler = ReflectUtil.newInstance(msgType.getAClass(), session, testSocketDTO);
        baseMessageHandler.handlerMessage();
    }

    @Override
    public void afterConnectionClosed(@NotNull WebSocketSession session, @NotNull CloseStatus status) {
        Long userId = (Long) session.getAttributes().get(WsAuthenticationInterceptor.attributeName);
        if (userId != null) {
            // 用户退出，移除缓存
            UserConnectWebsocketManager.removeAndClose(userId);
        }
    }

}
