import {defineStore} from "pinia";
import {ref} 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");
            console.log(spaces.value)
            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 await spaceService.fetchSpace(spaceId);
    };

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

        }

    }




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

})