import {defineStore} from 'pinia'
import {config} from '@/config'
import {useErrorStore} from "@/store/error.js";
import { useStageStore } from './stage.js'

export const usePropertySetsStore = defineStore('propertySets', {
    state() {
        return {
            periods: null,
            selectedPeriod: null,
        }
    },
    getters: {
        getPeriods(state) {
            return state.periods;
        },
        getCurrentPeriodId(state) {
            if (state.periods === null)
                return null;

            for (const period of state.periods) {
                if (period.state === "DRAFT")
                    return period.id;
            }

            for (const period of state.periods) {
                if (period.state === "VALID")
                    return period.id;
            }
        },
        getSelectedPeriod(state) {
            return state.selectedPeriod;
        },
        getPeriodState(state) {
            return function(periodId) {
                if (state.periods === null)
                    return null;

                return state.periods.find(p => p.id === periodId)?.state;
            }
        }
    },
    actions: {
        setSelectedPeriod(periodId) {
          this.selectedPeriod = periodId;
        },
        async invalidate() {

            const url = `${config.backendUrl}/properties/periods/${this.getSelectedPeriod}/`;
            this.periods = await this.performRequest('DELETE', url, null, false);

            await this.reload();

        },
        async loadPeriods() {
            this.loading = true;
            const url = `${config.backendUrl}/properties/periods`;
            this.periods = await this.performRequest('GET', url, null, );
            this.selectedPeriod = this.getCurrentPeriodId;
            this.loading = false;
        },
        async performRequest(method, url, body, expectResponse = true) {

            const params = {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                }
            };

            if ((body ?? null) !== null) {
                params.body = JSON.stringify(body);
            }

            const request = {url: url, params: params};
            console.log("Request:", request);

            const response = await fetch(url, params
            ).catch(e => {
                const error = {
                    code: 'Network error.',
                    message: "Please check your internet connection.",
                    trace: null
                }

                console.error(error);
                const errorStore = useErrorStore();
                void errorStore.addError(error, {store: this, request: request});

                throw e;
            });

            let data = null;
            if (expectResponse) {
                data = await response.json().catch(e => {
                    const error = {
                        code: 'Malformed response',
                        message: "Malformed server response. Please contact support.",
                        trace: null
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, request: request});
                    throw e;
                });

                if (!response.ok) {
                    const error = {
                        code: data.error.code,
                        title: data.error.title,
                        message: data.error.message,
                        trace: data.error.trace
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, request: request});
                    throw new Error('Internal backend error');
                }
            } else {
                if (!response.ok) {

                    const data = await response.json().catch(e => {
                        const error = {
                            code: "Return code error " + response.status,
                            message: "Server returned wrong response code",
                            trace: null
                        }
                        console.error(error);
                        const errorStore = useErrorStore();
                        void errorStore.addError(error, {store: this, request: request});
                        throw new Error('Internal backend error');

                    });

                    const error = {
                        code: data.error.code,
                        title: data.error.title,
                        message: data.error.message,
                        trace: data.error.trace
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, request: request});
                    throw new Error('Internal backend error');


                }
            }

            console.log("Response:", data);
            return data;
        }
    }
});