import SseSource from "~/services/sse/sseSource";
import {useAccessProfileStore} from "~/stores/accessProfile";
import {useSseStore} from "~/stores/sse";

/**
 * Setup SSE EventSource, allowing the app to listen for Mercure updates
 * /!\ This has to be executed client side
 *
 * @param ctx
 */
export default defineNuxtPlugin(nuxtApp => {
    const runtimeConfig = useRuntimeConfig()

    if (!runtimeConfig.baseUrlMercure) {
        console.error('Mercure : the hub url is not defined')
        return;
    }

    const accessProfile = useAccessProfileStore()
    const sseStore = useSseStore()

    const sseSource = new SseSource(
        runtimeConfig.baseUrlMercure,
        "access/" + accessProfile.id,
        () => { sseStore.connected = true },
        (eventData) => { sseStore.addEvent(eventData as any) },
        () => { sseStore.connected = false },
    )

    sseSource.subscribe()
    window.addEventListener('beforeunload', () => { sseSource.unsubscribe() })
})



