import {defineStore} from "pinia";
import {Ref, ref} from "@vue/reactivity";
import {useEntityManager} from "~/composables/data/useEntityManager";
import {MercureEntityUpdate} from "~/types/interfaces";

export const useSseStore = defineStore('sse', () => {
  const connected: Ref<boolean> = ref(false)
  const events: Ref<Array<MercureEntityUpdate>> = ref([])

  const addEvent = async (event: MercureEntityUpdate) => {
    const {em} = useEntityManager()

    const model = em.getModelFromIri(event.iri)

    switch (event.operation) {
      case "update":
      case "create":
        await em.save(model, JSON.parse(event.data), true)
        break

      case "delete":
        break

      default:
        throw new Error('SSE: unknown operation type')
    }
  }

  return {
    connected,
    events,
    addEvent
  }
})
