/*---------------------------------------------------------------------------------------------
 * 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
 */
import { useCallback, useRef, useSyncExternalStore } from "react";
import { SyncUiEventDispatcher } from "../syncui/SyncUiEventDispatcher.js";
/** Duck type the conditional. */
function isConditionalValue(conditionalProp) {
    return (typeof conditionalProp === "object" &&
        conditionalProp &&
        "syncEventIds" in conditionalProp &&
        "refresh" in conditionalProp &&
        "value" in conditionalProp);
}
/** @internal */
export function useConditionalProp(conditionalProp) {
    const refreshedRef = useRef(false);
    const subscribe = useCallback((onStoreChange) => {
        if (isConditionalValue(conditionalProp)) {
            return SyncUiEventDispatcher.onSyncUiEvent.addListener(({ eventIds }) => {
                if (!SyncUiEventDispatcher.hasEventOfInterest(eventIds, conditionalProp.syncEventIds))
                    return;
                if (!conditionalProp.refresh())
                    return;
                onStoreChange();
            });
        }
        return () => { };
    }, [conditionalProp]);
    const getSnapshot = useCallback(() => {
        if (isConditionalValue(conditionalProp)) {
            if (!refreshedRef.current) {
                conditionalProp.refresh();
                refreshedRef.current = true;
            }
            return conditionalProp.value;
        }
        return conditionalProp;
    }, [conditionalProp]);
    return useSyncExternalStore(subscribe, getSnapshot);
}
//# sourceMappingURL=useConditionalProp.js.map