import {defineStore} from "pinia";
import {ref, watch} from "vue";

import {spaceService} from "@/services/space-service";
import {Space} from "@/models/space";

export const useSpaceStore = defineStore('space', () => {
    const spaces = ref<Space[]>([]);
    const getSpaces = async () => {
        await spaceService.fetchSpaces().then((res) => {
            spaces.value = res;
            const spaceId = localStorage.getItem("spaceId");
            const selectedSpace =  spaces.value.find((s: Space) => s.id.toString() === spaceId) || null;
            selectedSpaceId.value = selectedSpace?.id;
            selectedSpaceName.value = selectedSpace?.name;
        })
        return spaces.value;
    }

    const selectedSpaceId = ref<number | undefined>(undefined);
    const selectedSpaceName = ref<string | undefined>(undefined);


    const getSpace = async () => {
        const spaceId = selectedSpaceId.value;
        if (!spaceId) {
            return null;
        }

       return spaceService.fetchSpace(spaceId);
    };

    const setSpace = (newSpaceId: number, newSpaceName: string) => {
        if (selectedSpaceId.value != newSpaceId) {
            selectedSpaceId.value = newSpaceId;
            selectedSpaceName.value = newSpaceName;
            localStorage.setItem("spaceId", newSpaceId.toString());

        }

    }


    return {spaces, getSpaces, getSpace, selectedSpaceId, selectedSpaceName, setSpace};

})