import store from "@/store";
import baseMixin from "@/mixins/base-mixin.js";
import { storeActions } from "@/constants/store-actions";
import { damageLocationsSelected as glassLocations } from "@/constants/damage-locations-selected";

export function getDamageString() {
    // If it's a repair it's always a windshield.
    const isRepair = store.getters.damage.isRepair;
    if (isRepair) {
        return "windshield";
    }

    const damageLocations = store.getters.damage.glassToReplace;

    let returnString;
    if (!damageLocations) {
        return;
    }

    if (damageLocations.length > 1) {
        returnString = "match";
    } else {
        switch (damageLocations[0]?.glassLocation) {
            case "Windshield":
                returnString = "windshield";
                break;
            case "Driver":
            case "Passenger":
                returnString = "side window";
                break;
            case "Rear":
                returnString = "rear window";
        }
    }
    return returnString;
}

export function getIsWindshieldOnly() {
    const damageLocations = store.getters.damage.glassToReplace;
    const returnString =
        damageLocations &&
        damageLocations.length === 1 &&
        damageLocations[0]?.glassLocation === "Windshield"
            ? "windshield"
            : "glass";
    return returnString;
}

export function includesWindshieldReplacement() {
    const windshieldMatches =
        store.getters.order.damage.glassToReplace?.filter(
            (glassToReplace) => glassToReplace.glassLocation === glassLocations.WINDSHIELD
        ) ?? [];
    return windshieldMatches.length > 0;
}

export async function isGlassAvailableForCarId(carId, pageNameToLog) {
    const newGlassOptions = await baseMixin.methods.dispatchStoreActionWithLogging(
        storeActions.GET_DAMAGE_OPTIONS,
        { carId: carId },
        pageNameToLog
    );

    const currentGlassOptions = store.getters.damage.glassToReplace;

    const optionsMap = {
        Windshield: "windshieldOptions",
        Driver: "driverSideOptions",
        Passenger: "passengerSideOptions",
        Rear: "backGlassOptions",
    };

    for (const option of currentGlassOptions) {
        if (
            !newGlassOptions.data[
                optionsMap[option.glassLocation]
            ].availableReplacementOptions.includes(option.glassName)
        ) {
            return false;
        }
    }

    return true;
}
