import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import performRequest from "@/backend.js";
import logger from "@/logger.js";

export const usePremiseStore = defineStore('premise', {
    state: () => ({
        premises: [],
        selectedIds: [],
        loading: false,
        empty: true,
        error: null,
        query: {},
        pagination: {}
    }),
    getters: {
        getById: (state) => {
            return (id) => state.premises.find(p => p.id === id)
        },
        isChecked(state) {
            return function (premiseId) {
                return state.selectedIds.includes(premiseId);
            }
        },
        allChecked(state) {
            if (state.premises.length > state.selectedIds.length)
                return false;

            for (const premise of state.premises) {
                if (!state.selectedIds.includes(premise.id))
                    return false;
            }

            return state.premises.length !== 0;
        },
        globallySomeChecked(state) {
            return state.selectedIds.length > 0;
        },
        someChecked(state) {
            for (const premise of state.premises) {
                if (state.selectedIds.includes(premise.id))
                    return true;
            }

            return false;
        },
        showData: (state) => !state.loading && state.empty === false,
        showLoading: (state) => state.loading,
        showEmpty: (state) => !state.loading && state.empty === true,
    },
    actions: {
        async createDrafts(ids) {
            const params = new URLSearchParams();
            params.append('premissIds', ids.join(', '));
            const data = await performRequest(this, "GET", `${config.backendUrl}/calculation/duplicate/${params.size === 0 ? '' : '?'}${params.toString()}`, null, true)

            return data.data;
        },
        async resolveStatus() {
            const params = new URLSearchParams();
            params.append('premissIds', this.selectedIds.join(', '));

            const data = await performRequest(this, 'GET', `${config.backendUrl}/calculation/resolve/${params.size === 0 ? '' : '?'}${params.toString()}`, null, true);
            return data.data;
        },
        resetSelectedIds() {
            this.selectedIds = [];
        },
        setChecked(premiseId, checked) {
            if (checked) {
                if (!this.selectedIds.includes(premiseId)) {
                    this.selectedIds.push(premiseId);
                }
            } else {
                const idx = this.selectedIds.indexOf(premiseId);
                if (idx !== -1)
                    this.selectedIds.splice(idx, 1);
            }
        },
        async setQuery(query) {
            this.query = query;
            await this.updatePremises();
        },
        async deletePremisses(ids) {

            ids.forEach(id => this.setChecked(id, false));

            const params = new URLSearchParams();
            params.append('premissIds', ids.join(', '));
            await performRequest(this, 'POST', `${config.backendUrl}/calculation/delete/${params.size === 0 ? '' : '?'}${params.toString()}`, null, false);
            await this.updatePremises();
        },
        async archivePremisses(ids) {
            const params = new URLSearchParams();
            params.append('premissIds', ids.join(', '));
            await performRequest(this, 'POST', `${config.backendUrl}/calculation/archive/${params.size === 0 ? '' : '?'}${params.toString()}`, null, false);
            await this.updatePremises();
        },
        async updatePremises() {

            this.premises = [];
            this.loading = true;
            this.empty = true;

            const params = new URLSearchParams();

            if (this.query.searchTerm)
                params.append('filter', this.query.searchTerm);

            if (this.query.archived)
                params.append('archived', this.query.archived);

            if (this.query.done)
                params.append('done', this.query.done);

            if (this.query.draft)
                params.append('draft', this.query.draft);

            if (this.query?.page)
                params.append('page', this.query.page);

            if (this.query?.pageSize)
                params.append('limit', this.query.pageSize);

            const url = `${config.backendUrl}/calculation/view/${params.size === 0 ? '' : '?'}${params.toString()}`;

            const {data: data, headers: headers} = await performRequest(this, 'GET', url, null, true);

            this.pagination = {
                page: parseInt(headers.get('X-Current-Page')),
                pageCount: parseInt(headers.get('X-Page-Count')),
                totalCount: parseInt(headers.get('X-Total-Count'))
            };

            logger.log("pagination (premise store)", this.pagination);

            this.loading = false;
            this.empty = data.length === 0;
            this.premises = data;

        }
    }
})