<template>
    <div>

    </div>
</template>
<script setup>
import { Stomp } from "@stomp/stompjs";
import SockJS from 'sockjs-client/dist/sockjs';
import { onBeforeUnmount, onMounted, ref } from 'vue';

// Define props
const props = defineProps(['topic', 'subtopic']);
const emit = defineEmits(['update']);



// Reactive state
const lastMessage = ref({ message: "" });
let stompClient = null;
let messageHandler = null;

//Function to connect to websocket
const connectWebSocket = (onMessageReceived) => {
    messageHandler = onMessageReceived; // Store the message handler

    if (stompClient !== null) {
        console.warn('Websocket is already Connected.');
        return;
    }

    const socket = new SockJS(`${import.meta.env.VITE_BACKEND_URL}/ws/endpoint`);
    stompClient = Stomp.over(socket);
    stompClient.reconnect_delay = 5000;
    stompClient.connect({}, (frame) => {
        //console.log('Connected: '+frame); 

        // Correctly use props.topic and props.subtopic
        const subscriptionTopic = `/${props.topic}/${props.subtopic}`;
        console.log('Subscribing to: ' + subscriptionTopic);

        stompClient.subscribe(subscriptionTopic, (message) => {
            if (messageHandler) {
                messageHandler(JSON.parse(message.body));
            }
        });
    }, (error) => {
        console.warn('WebSocket Error: ' + error);
    });


};

onMounted(() => {
    console.log("Created notification component");
    connectWebSocket(handleWebSocketMessage)
});

onBeforeUnmount(() => {
    if (stompClient !== null) {
        stompClient.disconnect(() => {
            console.log('Disconnected');
        })
        stompClient = null;
    }
});

const handleWebSocketMessage = (data) => {
    console.log('Received WebSocket message: ', data)
    lastMessage.value = data;
    emit('update', data);
}
</script>