package cn.reghao.bnt.web.ws.handler;

import cn.reghao.bnt.web.devops.machine.util.Keys;
import cn.reghao.bnt.web.devops.machine.util.WebSsh;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

/**
 * @author reghao
 * @date 2021-02-10 22:33:52
 */
@Slf4j
@Component
public class SshWebSocketHandler implements WebSocketHandler {
    private final WebSsh webSsh;

    public SshWebSocketHandler(WebSsh webSsh) {
        this.webSsh = webSsh;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) {
        log.info("用户 {} 连接 WebSSH", webSocketSession.getAttributes().get(Keys.USER_UUID));
        webSsh.init(webSocketSession);
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) {
        if (webSocketMessage instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) webSocketMessage;
            log.info("用户 {} 通过 WebSSH 发送 {} 命令",
                    webSocketSession.getAttributes().get(Keys.USER_UUID), webSocketMessage.getPayload());
            webSsh.handleMessage(textMessage.getPayload(), webSocketSession);
        } else if (webSocketMessage instanceof BinaryMessage) {
            log.info("二进制消息");
        } else if (webSocketMessage instanceof PongMessage) {
        } else {
            log.error("未知类型的 WebSocket 消息");
        }
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) {
        log.error("WebSocket 数据传输错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) {
        log.info("用户 {} 断开 WebSSH 连接", webSocketSession.getAttributes().get(Keys.USER_UUID));
        webSsh.close(webSocketSession);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
