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

let stompClient = null;

export function connectToWebSocket(onMessageReceived) {
    const socket = new WebSocket('ws://'+__LOCAL_IP__+':8010/ws'); // 后端 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.onStompError = (error) => {
        console.error('STOMP Error:', error.headers.message);
    };

    stompClient.activate();
}
