import {defineStore} from 'pinia'
import {config} from '@/config'
import performRequest, {performDownload} from '@/backend.js'


export const useReportsStore = defineStore('reports', {
        state() {
            return {
                reports: [],
                showComparableWarning: false,
                loading: false,
                materialId: null,
                supplierIds: [],
                userSupplierIds: [],
            }
        },
        getters: {
            getShowComparableWarning(state) {
              return state.showComparableWarning;
            },
            getChartScale(state) {
                let max = 0;

                state.reports.forEach(report => {
                    max = Math.max(report.risk.mek_b.total, max);
                    max = Math.max(report.risk.risk_scenario.total, max);
                })

                const magnitude = Math.pow(10, Math.floor(Math.log10(max)));
                return Math.ceil(max / magnitude) * magnitude;
            }
        },
        actions: {
            async downloadReport() {

                if(this.materialId === null && this.supplierIds?.length === 0)
                    return;

                const params = new URLSearchParams();
                params.append('material', this.materialId);
                params.append('sources', this.supplierIds);
                params.append('userSources', this.userSupplierIds);

                const url = `${config.backendUrl}/reports/download/${params.size === 0 ? '' : '?'}${params.toString()}`;
                const fileName = `report_${this.materialId}_${this.supplierIds.join('_')}_u${this.userSupplierIds.join('_')}.xlsx`;
                await performDownload(url,fileName);
            },
            reset() {
                this.reports = [];
            },
            async fetchReports(materialId, supplierIds, userSupplierIds) {
                if (supplierIds == null || materialId == null) return;

                this.loading = true;
                this.reports = [];

                this.materialId = materialId;
                this.supplierIds = supplierIds;
                this.userSupplierIds = userSupplierIds;

                const params = new URLSearchParams();
                params.append('material', materialId);
                params.append('sources', supplierIds);
                params.append('userSources', userSupplierIds);

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

                const {data: data} = await performRequest(this, 'GET', url, null).catch(e => {
                    this.loading = false;
                });
                this.reports = data;


                this.showComparableWarning = false;
                for (const [idx, report] of this.reports.entries()) {
                    for (const otherReport of this.reports.slice(idx + 1)) {
                        if (report.premises.length !== otherReport.premises.length) {
                            this.showComparableWarning = true;
                            break;
                        }

                        for (const premise of report.premises) {

                            const otherPremise = otherReport.premises.find(otherPremise => otherPremise.destination.external_mapping_id === premise.destination.external_mapping_id);

                            if((otherPremise ?? null) == null) {
                                this.showComparableWarning = true;
                                break;
                            }

                            if(otherPremise.annual_quantity !== premise.annual_quantity) {
                                this.showComparableWarning = true;
                                break;
                            }

                        }

                    }

                    if(this.showComparableWarning)
                        break;
                }


                this.loading = false;
            }
        }
    }
);