package com.ruoyi.common.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WebSocketSender implements WebSocketHandler {

    private WebSocketSession session;
    private final Object lock = new Object(); // 同步锁

//    public static void main(String[] args) throws Exception {
//        WebSocketClient client = new StandardWebSocketClient();
//        WebSocketConnectionManager manager = new WebSocketConnectionManager(
//                client,
//                new WebSocketSender(),
//                "ws://www.hxzpw.net:7066"
//        );
//        manager.start();
////        Thread.sleep(5000); // 保持连接
//    }

    public static void main(String[] args) throws Exception {
        WebSocketSender sender = new WebSocketSender();
        sender.connect("ws://www.hxzpw.net:7066");

        // 发送文本消息
        Thread.sleep(1000); // 确保连接建立
        sender.sendMessage("Hello WebSocket!");
    }

    public void connect(String serverUri) {
        WebSocketConnectionManager manager = new WebSocketConnectionManager(
                new StandardWebSocketClient(),
                this,
                serverUri
        );
        manager.start();
        System.out.println("Connecting to {" + serverUri + "}");
    }

    public void sendMessage(String message) {
        synchronized (lock) {
            try {
                CompletableFuture<String> responseFuture = new CompletableFuture<>();
                session.sendMessage(new TextMessage(message));
                String receive = responseFuture.get(5, TimeUnit.SECONDS);
                System.out.println("Sent message: " + message);
                System.out.println("Receive message: " + receive);
            } catch (Exception e) {
                log.error("WebSocket 发送信息异常: {}", e.getMessage());
            }
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
        log.info("WebSocket 连接已建立: {}", session.getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        this.session = null;
        log.error("连接已关闭: {}", closeStatus.getReason());
    }

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