import {defineStore} from "pinia";
import {ref, watch} from "vue";
import {EventBus} from "@/utils/EventBus";
import {getSpaces} from "@/services/spaceService";
import {Space} from "@/models/Space";

export const useSpaceStore = defineStore('space', () => {
    const spaces = ref();
    const fetchSpaces = async () => {
        await getSpaces().then((res) => {
            spaces.value = res;
            const spaceId = localStorage.getItem("spaceId");
            space.value = spaces.value.find((s: Space) => s.id === spaceId) || null;
        })
    }

    const space = ref<Space | null>(null);


    const getSpace = async () => {
        const spaceId = localStorage.getItem("spaceId");
        if (!spaceId) {
            return null;
        }

        if (!spaces.value || spaces.value.length === 0) {
            await fetchSpaces();
        }

        space.value = spaces.value.find((s) => s.id === spaceId) || null;
        return space.value;
    };

    const setSpace = (newSpace: Space | null) => {
        if (newSpace != space) {
            space.value = newSpace;
            localStorage.setItem("spaceId", newSpace.id)
            EventBus.emit("spaceChanged", space);
        }

    }


    return {spaces, fetchSpaces, getSpace, space, setSpace};

})