import { IGXE } from "@intelligentgraphics/igd.core";
/**
 * Finds all articles where a specific value for a property could be set
 *
 * @param {Article[]} objects
 * @param {string} propertyKey
 * @param {IGXE.TPropertyValue} propertyValue
 * @returns {string[]} comIds
 */
export const findApplyTargets = (objects, propertyKey, propertyValue) => {
    const targetable = [];
    const normalizedValue = propertyValue.toString();
    const rawValuePath = IGXE.getPropertyNamesFromKey(normalizedValue);
    const valueParentProperty = rawValuePath.length <= 1
        ? propertyKey
        : rawValuePath[rawValuePath.length - 2];
    const rootPropertyKey = IGXE.getPropertyNamesFromKey(propertyKey)[0];
    const valueEqualsNormalized = ({ Value }) => Value.toString() === normalizedValue;
    for (const articleInstance of objects) {
        if (articleInstance.configuration[rootPropertyKey] === propertyValue) {
            continue;
        }
        const propertyData = IGXE.findProperty(articleInstance.properties, valueParentProperty);
        if (propertyData === undefined) {
            continue;
        }
        if (normalizedValue.match(/^[\d\.]+$/) &&
            propertyData.ValueRangeFrom !== undefined &&
            propertyData.ValueRangeTo !== undefined) {
            const numValue = parseFloat(normalizedValue);
            if (numValue > propertyData.ValueRangeTo ||
                numValue < propertyData.ValueRangeFrom) {
                continue;
            }
        }
        if (propertyData.Values &&
            propertyData.Values.length &&
            !propertyData.Values.find(valueEqualsNormalized)) {
            continue;
        }
        targetable.push(articleInstance);
    }
    return targetable;
};
