import * as React from "react";
import { IGXE } from "@intelligentgraphics/igd.core";
import { parsePropertyIdentifier, createPropertyIdentifier } from "../Util";
import { usePropertyEditorContext } from "../Context";
/**
 * Provides the current data and manipulation methods for a single property editor property
 *
 * @param {string} identifier
 * @returns {(PropertyViewProps | undefined)}
 */
export const usePropertyEditorProperty = (identifier) => {
    const context = usePropertyEditorContext();
    // since the property editor only stores the direct properties of articles, we first need to find the root property name,
    // so that we can descend its tree and find the actual property
    const rootPropertyIdentifier = React.useMemo(() => {
        const { groupId, propertyKey } = parsePropertyIdentifier(identifier);
        const [rootPropertyName] = IGXE.getPropertyNamesFromKey(propertyKey);
        return createPropertyIdentifier(groupId, rootPropertyName);
    }, [identifier]);
    const property = React.useMemo(() => {
        const { propertyKey } = parsePropertyIdentifier(identifier);
        const rootProperty = context.properties[rootPropertyIdentifier];
        if (rootProperty === undefined) {
            return undefined;
        }
        return IGXE.findProperty([rootProperty], propertyKey);
    }, [identifier, context.properties]);
    // values are always set directly on the root property
    const functions = React.useMemo(() => ({
        setPropertyValue: (value) => context.setPropertyValue(rootPropertyIdentifier, value),
        applyToAll: () => context.applyToAll(rootPropertyIdentifier),
    }), [rootPropertyIdentifier]);
    if (property === undefined) {
        return undefined;
    }
    return {
        ...property,
        ...functions,
    };
};
const Property = props => {
    const data = usePropertyEditorProperty(props.identifier);
    if (data === undefined) {
        return null;
    }
    return props.children(data);
};
Property.displayName = "Property";
export default Property;
