package cd.casic.module.terminal.websocket;

import cd.casic.framework.websocket.core.listener.WebSocketMessageListener;
import cd.casic.module.terminal.define.AssetThreadPools;
import cd.casic.module.terminal.host.terminal.enums.InputTypeEnum;
import cd.casic.module.terminal.host.terminal.manager.TerminalManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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.AbstractWebSocketHandler;


/**
 * 终端处理器
 *
 * @author Yuru Pu
 * @version 1.0
 * @since 2025/7/4 16:28
 */
@Slf4j
@Component
public class TerminalWebSocketMessageListener implements WebSocketMessageListener<TextMessage> {

    @Resource
    private TerminalManager terminalManager;
    @Override
    public void onMessage(WebSocketSession session, TextMessage message) {
        handleTextMessage(session, message);
    }

    @Override
    public String getType() {
        return "terminal-access-message-send";
    }


    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        try {
            // 解析类型
            InputTypeEnum type = InputTypeEnum.of(payload);
            if (type == null) {
                return;
            }
            // 解析并处理消息
            if (type.isAsyncExec()) {
                // 异步执行
                AssetThreadPools.TERMINAL_OPERATOR.execute(() -> {
                    type.getHandler().handle(session, type.parse(payload));
                });
            } else {
                // 同步执行
                type.getHandler().handle(session, type.parse(payload));
            }
        } catch (Exception e) {
            log.error("TerminalDispatchHandler-handleMessage-error id: {}, msg: {}", session.getId(), payload, e);
        }
    }

    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String id = session.getId();
        log.info("TerminalMessageDispatcher-afterConnectionClosed id: {}, code: {}, reason: {}", id, status.getCode(), status.getReason());
        // 关闭会话
        terminalManager.closeSession(id);
    }

}
