package com.hys.app.framework.ws.impl;

import com.hys.app.framework.ws.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * Websocket的Handler，处理所有websocket相关消息，包括连接成功、连接关闭、收到文本消息等
 * Author: Dawei
 * Datetime: 2022-07-18 14:52
 */
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private SessionManager sessionManager;

    /**
     * Websocket连接成功时，将WebSocketSession加入缓存
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.debug("建立连接{}", session);
        sessionManager.addSession(session);

    }

    /**
     * 收到文本消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        logger.debug("handle text{} by session:{}", message,session);
        super.handleTextMessage(session, message);
        if (message.getPayloadLength() == 0) {
            session.sendMessage(new TextMessage(""));
            return;
        }
    }

    /**
     * 连接出错时，从缓存中移除WebSocketSession
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.debug("连接出错{}", session);

        sessionManager.removeSession(session);
    }

    /**
     * 连接关闭时，从缓存中移除WebSocketSession
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.debug("断开连接{}", session);
        sessionManager.removeSession(session);
    }
}