import partTypeStrings from '@/constants/part-type-strings';
import { deepClone } from '@/helpers/object-helper';

const recalPartTypes = [partTypeStrings.RECALIBRATION, partTypeStrings.ADAS_RECALIBRATION];

export function isRecalPart(part) {
    return recalPartTypes.some((type) => type === part.partType);
}

export function isRecalPartOrHasChildRecalPart(glassPart) {
    const isGlassPartRecalPart = isRecalPart(glassPart);

    if (!isGlassPartRecalPart && glassPart.childParts && glassPart.childParts.length > 0) {
        return glassPart.childParts.filter((cp) => isRecalPartOrHasChildRecalPart(cp));
    }

    return isGlassPartRecalPart;
}

export function getTopLevelGlassPartsWithRecal(glassParts) {
    if (!glassParts) {
        return null;
    }

    return glassParts.filter((gp) => isRecalPartOrHasChildRecalPart(gp));
}

export function getItemsWithoutRecalParts(lineItemsArray) {
    if (!lineItemsArray || !Array.isArray(lineItemsArray)) return null;
    const firstLevelFiltered = deepClone(lineItemsArray).filter((li) => !isRecalPart(li));

    const childrenFiltered = firstLevelFiltered.map((li) => {
        if (li.childParts && li.childParts.length > 0) {
            li.childParts = getItemsWithoutRecalParts(li.childParts);
        }

        return li;
    });

    return childrenFiltered;
}

export function getRecalPartNumbers(glassPartsArray) {
    if (glassPartsArray && glassPartsArray.length > 0) {
        const topLevel = glassPartsArray.filter((gp) => isRecalPart(gp)).map((gp) => gp.partNumber);

        const children = glassPartsArray.map((gp) => getRecalPartNumbers(gp.childParts)).flat();

        return [...topLevel, ...children];
    } else {
        return [];
    }
}

