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

/**
 * 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.public.baseUrlMercure) {
        console.error('Mercure : the hub url is not defined')
        return;
    }

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

    const onOpen = () => sseStore.connected = true
    const onClose = () => sseStore.connected = false

    const onMessage = (eventData: AnyJson) => {
        sseStore.addEvent(eventData as any)
    }

    const sseSource = new SseSource(
        runtimeConfig.public.baseUrlMercure,
        "access/" + accessProfile.id,
        onOpen,
        onMessage,
        onClose,
    )

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



