"use strict";
/*---------------------------------------------------------------------------------------------
 * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
 * See LICENSE.md in the project root for license terms and full copyright notice.
 *--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Utilities
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConditionalProp = void 0;
const React = require("react");
const shim_1 = require("use-sync-external-store/shim");
const SyncUiEventDispatcher_1 = require("../syncui/SyncUiEventDispatcher");
/** Duck type the conditional. */
function isConditionalValue(conditionalProp) {
    return (typeof conditionalProp === "object" &&
        conditionalProp &&
        "syncEventIds" in conditionalProp &&
        "refresh" in conditionalProp &&
        "value" in conditionalProp);
}
/** @internal */
function useConditionalProp(conditionalProp) {
    const subscribe = React.useCallback((onStoreChange) => {
        if (isConditionalValue(conditionalProp)) {
            return SyncUiEventDispatcher_1.SyncUiEventDispatcher.onSyncUiEvent.addListener(({ eventIds }) => {
                if (!SyncUiEventDispatcher_1.SyncUiEventDispatcher.hasEventOfInterest(eventIds, conditionalProp.syncEventIds))
                    return;
                if (!conditionalProp.refresh())
                    return;
                onStoreChange();
            });
        }
        return () => { };
    }, [conditionalProp]);
    const getSnapshot = React.useCallback(() => {
        if (isConditionalValue(conditionalProp))
            return conditionalProp.value;
        return conditionalProp;
    }, [conditionalProp]);
    return (0, shim_1.useSyncExternalStore)(subscribe, getSnapshot);
}
exports.useConditionalProp = useConditionalProp;
//# sourceMappingURL=useConditionalProp.js.map