import {Plugin} from "@nuxt/types";
import SseSource from "~/services/sse/sseSource";

/**
 * Setup SSE EventSource, allowing the app to listen for Mercure updates
 * /!\ This has to be executed client side
 *
 * @param ctx
 */
const ssePlugin: Plugin = ({ $config, store }) => {
  const sseSource = new SseSource(
    $config.baseUrl_mercure,
    "access/" + store.state.profile.access.id,
    () => { store.commit('sse/setConnected', true) },
    (eventData) => { store.commit('sse/addEvent', eventData) },
    () => { store.commit('sse/setConnected', false) },
  )

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

export default ssePlugin
