import {defineStore} from 'pinia'
import {config} from '@/config'
import {useErrorStore} from "@/store/error.js";
import { useStageStore } from './stage.js'
import {usePropertySetsStore} from "@/store/propertySets.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;

            console.log(property)

            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 this.performRequest('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()}`;
            this.properties = await this.performRequest('GET', url, null);
            this.loadedPeriod = period;

            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;
        }
    }
});