"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEntityDetails = void 0;
var react_1 = require("react");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var useSafePromise_1 = require("../hooks/useSafePromise");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
var useEntityDetails = function (entityUri) {
    var _a = (0, react_1.useState)(null), entityDetails = _a[0], setEntityDetails = _a[1];
    var _b = (0, react_1.useState)(false), isLoading = _b[0], setIsLoading = _b[1];
    var safePromise = (0, useSafePromise_1.useSafePromise)();
    var cancelRequest = (0, react_1.useCallback)(function () { return safePromise(Promise.resolve()); }, [safePromise]);
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    var showMasking = (0, MdmModuleContext_1.useMdmShowMasking)();
    var entityOptions = (0, react_1.useMemo)(function () { return (0, mdm_sdk_1.addGetEntityMaskingOptions)(metadata, { showMasking: showMasking, showAccess: false }); }, [metadata, showMasking]);
    var showEntityDetails = (0, react_1.useCallback)((0, mdm_sdk_1.debounce)(function () {
        setIsLoading(true);
        safePromise((0, mdm_sdk_1.getEntity)(entityUri, entityOptions))
            .then(setEntityDetails)
            .catch(function (error) {
            console.warn('Failed to load entity', error);
        })
            .finally(function () { return setIsLoading(false); });
    }, 1000), [entityUri, safePromise, entityOptions]);
    var hideEntityDetails = (0, react_1.useCallback)(function () {
        cancelRequest();
        showEntityDetails.cancel();
        setIsLoading(false);
        setEntityDetails(null);
    }, [showEntityDetails, cancelRequest]);
    (0, react_1.useEffect)(function () {
        return function () { return showEntityDetails.cancel(); };
    }, []);
    return {
        isLoading: isLoading,
        entityDetails: entityDetails,
        showEntityDetails: showEntityDetails,
        hideEntityDetails: hideEntityDetails
    };
};
exports.useEntityDetails = useEntityDetails;
