import {defineStore} from 'pinia'
import {toRaw} from "vue";

export const useDestinationSingleEditStore = defineStore('destinationSingleEdit', {
    state: () => ({
        destination: null,
    }),
    actions: {
        setDestination(from) {

            const temp = {};

            temp.id = `${from.id}`;
            temp.destination_node = structuredClone(toRaw(from.destination_node));
            temp.routes = structuredClone(toRaw(from.routes));

            temp.annual_amount = from.annual_amount;
            temp.is_d2d = from.is_d2d;
            temp.rate_d2d = from.is_d2d ? from.rate_d2d : null;
            temp.lead_time_d2d = from.is_d2d ? from.lead_time_d2d : null;
            temp.handling_costs = from.handling_costs;
            temp.disposal_costs = from.disposal_costs;
            temp.repackaging_costs = from.repackaging_costs;
            temp.userDefinedHandlingCosts = from.handling_costs !== null || from.disposal_costs !== null || from.repackaging_costs !== null;


            this.destination = temp;
        },
        copyBack(to) {


            to.id = parseInt(this.destination.id);

            to.annual_amount = this.destination.annual_amount;
            to.is_d2d = this.destination.is_d2d;
            to.rate_d2d = this.destination.is_d2d ? this.destination.rate_d2d : null;
            to.lead_time_d2d = this.destination.is_d2d ? this.destination.lead_time_d2d : null;

            if (this.destination.userDefinedHandlingCosts) {
                to.disposal_costs = this.destination.disposal_costs;
                to.repackaging_costs = this.destination.repackaging_costs;
                to.handling_costs = this.destination.handling_costs;
            } else {
                to.disposal_costs = null;
                to.repackaging_costs = null;
                to.handling_costs = null;
            }

            if ((this.destination.routes ?? null) !== null) {
                to.routes.forEach(route => route.is_selected = this.destination.routes.find(r => r.id === route.id)?.is_selected ?? false);
            }

            return to;
        }
    },
});