import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import { useStageStore } from './stage.js'
import {usePropertySetsStore} from "@/store/propertySets.js";
import performRequest from "@/backend.js";

export const usePropertiesStore = defineStore('properties', {
    state() {
        return {
            periods: null,
            properties: null,
            loadedPeriod: null,
            loading: false,

        }
    },
    getters: {
        isLoading(state) {
            return state.loading;
        },
        getProperties(state) {
            return state.properties;
        },
    },
    actions: {
        async reload() {
            await this.loadProperties();

            const periods = usePropertySetsStore();
            await periods.loadPeriods();

            const stage = useStageStore();
            await stage.checkStagedChanges();
        },
        async setProperty(property) {
            if(this.properties === null) return;

            const prop = this.properties.find(p => p.external_mapping_id === property.id);

            if((prop ?? null) === null) return;

            const url = `${config.backendUrl}/properties/system/${property.id}`;
            const body = { value: String(property.value)};

            await performRequest(this,'PUT', url, body, false);

            prop.draft_value = property.reset ? null : property.value;

            const stage = useStageStore();
            await stage.checkStagedChanges();

        },
        async loadProperties(period = null) {
            this.loading = true;

            const params = new URLSearchParams();
            if (period !== null)
                params.append('property_set', period);
            const url = `${config.backendUrl}/properties/${params.size === 0 ? '' : '?'}${params.toString()}`;
            const resp = await performRequest(this,'GET', url, null);
            this.properties = resp.data;
            this.loadedPeriod = period;

            this.loading = false;
        }
    }
});