import { __assign, __read } from "tslib";
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 var usePropertyEditorProperty = function (identifier) {
    var 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
    var rootPropertyIdentifier = React.useMemo(function () {
        var _a = parsePropertyIdentifier(identifier), groupId = _a.groupId, propertyKey = _a.propertyKey;
        var _b = __read(IGXE.getPropertyNamesFromKey(propertyKey), 1), rootPropertyName = _b[0];
        return createPropertyIdentifier(groupId, rootPropertyName);
    }, [identifier]);
    var property = React.useMemo(function () {
        var propertyKey = parsePropertyIdentifier(identifier).propertyKey;
        var 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
    var functions = React.useMemo(function () { return ({
        setPropertyValue: function (value) {
            return context.setPropertyValue(rootPropertyIdentifier, value);
        },
        applyToAll: function () { return context.applyToAll(rootPropertyIdentifier); },
    }); }, [rootPropertyIdentifier]);
    if (property === undefined) {
        return undefined;
    }
    return __assign(__assign({}, property), functions);
};
var Property = function (props) {
    var data = usePropertyEditorProperty(props.identifier);
    if (data === undefined) {
        return null;
    }
    return props.children(data);
};
Property.displayName = "Property";
export default Property;
