import { useState, useCallback, useEffect, useMemo } from 'react';
import { getEntity, debounce, addGetEntityMaskingOptions } from '@reltio/mdm-sdk';
import { useSafePromise } from '../hooks/useSafePromise';
import { useMdmMetadata, useMdmShowMasking } from '../contexts/MdmModuleContext';
export var useEntityDetails = function (entityUri) {
    var _a = useState(null), entityDetails = _a[0], setEntityDetails = _a[1];
    var _b = useState(false), isLoading = _b[0], setIsLoading = _b[1];
    var safePromise = useSafePromise();
    var cancelRequest = useCallback(function () { return safePromise(Promise.resolve()); }, [safePromise]);
    var metadata = useMdmMetadata();
    var showMasking = useMdmShowMasking();
    var entityOptions = useMemo(function () { return addGetEntityMaskingOptions(metadata, { showMasking: showMasking, showAccess: false }); }, [metadata, showMasking]);
    var showEntityDetails = useCallback(debounce(function () {
        setIsLoading(true);
        safePromise(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 = useCallback(function () {
        cancelRequest();
        showEntityDetails.cancel();
        setIsLoading(false);
        setEntityDetails(null);
    }, [showEntityDetails, cancelRequest]);
    useEffect(function () {
        return function () { return showEntityDetails.cancel(); };
    }, []);
    return {
        isLoading: isLoading,
        entityDetails: entityDetails,
        showEntityDetails: showEntityDetails,
        hideEntityDetails: hideEntityDetails
    };
};
