import { defineStore } from 'pinia'
// Function to process keys ending with '_old' and remove this part
function processKeys(data) {
    const result = {};
    Object.keys(data).forEach(key => {
        if (key.endsWith('_old')) {
            const newKey = key.replace('_old', ''); // Remove '_old' from the key
            result[newKey] = data[key]; // Assign the value to the new key in the result object
        } else {
            result[key] = data[key]; // Copy other keys as they are
        }
    });
    return result;
};
const useProductStore = defineStore("productStore", {
    state: () => {
        return {
            selectedRow: {},
            selectedRows: [],
            selectedStore: '',
            productsFilters: {},
            forecast_granularity:[],
            configurationParameters:{},
            customizedProducts: new Map(),
            customizationResults: new Map(),
            currency: '',
            webAppId: '',
            scenarioRunId: null,
            userRanOptimization: false,
            loading: false,
        }
    },
    getters: {
        hasSelectedRow(state) {
            return state.selectedRow && state.selectedRow.initial
        },
        productNames(state) {
            return Array.from(new Set(state.selectedRows.map(item => item.product_id)))
        },
        resultProdcutNames(state){
            return new Set([...state.customizedProducts.keys(), ...state.customizationResults.keys()]);
        },
        customizedRows(state){
            const output = [];
            state.customizedProducts.forEach( val => output.push(val.current))
            return output;
        }
    },
    actions: {
        // Define mutations to update the shared data
        selectRowToCustomize(rowName) {
            if (!rowName) {
                this.selectedRow = {}
            }
            if(this.customizedProducts.has(rowName)){
                this.selectedRow = this.customizedProducts.get(rowName)
            }else{
                this.selectedRow = { initial: this.selectedRows.filter(item => item.product_id == rowName)[0]}
            }
        },
        getRow(rowName){
            return this.selectedRows.filter(item => item.product_id == rowName)[0] 
        },
        getCustomizedRow(rowName){
            if(this.customizationResults.has(rowName)){
                return this.customizationResults.get(rowName)
            }else{
                return this.customizedProducts.get(rowName)
            }
        },
        addCustomizedRow(row){
            const index = this.selectedRows.findIndex(item => item.product_id === row.product_id)
            if(index > -1) this.customizedProducts.set(row.product_id, 
                { 
                    initial : { ...this.selectedRows[index] }, 
                    current : { ...this.selectedRows[index], ...row }
                });
        },
        appendResults(rows) {
            rows.forEach(row => {
                console.log("user ran opt:", this.userRanOptimization)
                // delete the row from locally customized rows if the row is inside results 
                //and the user ran the optimization
                // TODO improve this to delete it just in case there is a difference between local values and results
                if(this.userRanOptimization && this.customizedProducts.has(row.product_id)){
                    this.customizedProducts.delete(row.product_id);
                }
                let initial = processKeys(row)
                this.customizationResults.set(row.product_id, {
                    initial,
                    result: {...row}
                })
            })
        },
        deleteCustomizedRow(rowId){
            this.customizedProducts.delete(rowId)
        },
        addAllCustomizedProductsToSelectedRows() {
            this.customizedProducts.forEach((value, key) => {
                if(this.selectedRows.findIndex(item => item.product_id === value.initial.product_id) === -1){
                    this.selectedRows.push(value.initial);
                }
            });
        },
        addSelectedRows(rows){
            rows.forEach(el => {
                if(this.selectedRows.findIndex(item => item.product_id === el.product_id) === -1){
                    this.selectedRows.push(el);
                }
            })
        },
        removeSelectedRows(rows){
            rows.forEach(el => {
                if(this.selectedRows.findIndex(item => item.product_id === el.product_id) != -1){
                    this.selectedRows.pop(el);
                }
            })
        },
    },
});

export default useProductStore;
