package cd.casic.module.terminal.websocket;

import cd.casic.framework.websocket.core.listener.WebSocketMessageListener;
import cd.casic.framework.websocket.core.session.WebSocketSessionHandlerDecorator;
import cd.casic.framework.websocket.core.session.WebSocketSessionManager;
import cd.casic.module.terminal.host.transfer.ITransferHandler;
import cd.casic.module.terminal.host.transfer.TerminalTransferManager;
import cd.casic.module.terminal.host.transfer.TransferHandler;
import cd.casic.module.terminal.host.transfer.TransferOperatorRequest;
import cn.orionsec.kit.lang.utils.io.Streams;
import com.alibaba.fastjson.JSON;
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.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;



/**
 * sftp 传输消息处理器 文本处理
 *
 * @author Yuru Pu
 * @version 1.0
 * @since 2025/7/4 16:28
 */
@Slf4j
@Component
public class TransferWebSocketMessageListener implements WebSocketMessageListener<TextMessage>{

    @Resource
    private TerminalTransferManager terminalTransferManager;


    @Override
    public void onMessage(WebSocketSession session, TextMessage message) {
        afterConnectionEstablished(session);
        handleTextMessage(session, message);
    }

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


    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("TransferMessageHandler-afterConnectionEstablished id: {}", session.getId());
        // 添加处理器
        if (terminalTransferManager.getHandler(session.getId())==null) {
            terminalTransferManager.putHandler(session.getId(), new TransferHandler(session));
        }
    }

    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 获取处理器
        ITransferHandler handler = terminalTransferManager.getHandler(session.getId());
        // 处理消息
        handler.handleMessage(JSON.parseObject(message.getPayload(), TransferOperatorRequest.class));
    }
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String id = session.getId();
        log.info("TransferMessageHandler-afterConnectionClosed id: {}, code: {}, reason: {}", id, status.getCode(), status.getReason());
        // 关闭会话
        Streams.close(terminalTransferManager.removeHandler(id));
    }
}
