import { Client } from '@stomp/stompjs';

let stompClient = null;

export function connectToWebSocket(onMessageReceived) {
    const socket = new WebSocket(__LOCAL_IP__); // 后端 WebSocket 地址
    stompClient = new Client({
        webSocketFactory: () => socket,
        reconnectDelay: 5000,
        heartbeatIncoming: 4000,
        heartbeatOutgoing: 4000,
    });

    stompClient.onConnect = () => {

        stompClient.subscribe('/topic/announcements', (message) => {
            const announcement = JSON.parse(message.body);
            onMessageReceived(announcement);
        });
        // 删除公告的订阅
        stompClient.subscribe('/topic/del', (message) => {
            onMessageReceived("del");
        });
        // 修改公告的订阅
        stompClient.subscribe('/topic/update', (message) => {
            onMessageReceived("update");
        });
    };

    stompClient.onStompError = (error) => {
        console.error('STOMP Error:', error.headers.message);
    };

    stompClient.activate();
}
