import { useState, useEffect } from 'react';
import { addGetEntityMaskingOptions, getEntityTimeSlice, isEditableMode } from '@reltio/mdm-sdk';
import { useSafePromise } from '../../../hooks/useSafePromise';
import { useMdmAction, useMdmHistorySlice, useMdmMetadata, useMdmMode, useMdmShowMasking } from '../../../contexts/MdmModuleContext';
export var useHistorySlice = function (_a) {
    var entity = _a.entity, historyEvent = _a.historyEvent;
    var _b = useState(false), isLoading = _b[0], setIsLoading = _b[1];
    var setHistorySlice = useMdmAction('setHistorySlice');
    var clearHistoryEvent = useMdmAction('clearHistoryEvent');
    var metadata = useMdmMetadata();
    var historySlice = useMdmHistorySlice();
    var safePromise = useSafePromise();
    var mode = useMdmMode();
    var showMasking = useMdmShowMasking();
    var _c = historyEvent || {}, aStamp = _c.aStamp, bStamp = _c.bStamp, overrideUri = _c.overrideUri;
    var entityUri = overrideUri || (entity === null || entity === void 0 ? void 0 : entity.uri);
    useEffect(function () {
        if (isEditableMode(mode) && entityUri) {
            safePromise(Promise.resolve());
            clearHistoryEvent();
            setIsLoading(false);
        }
    }, [mode, entityUri]);
    useEffect(function () {
        if (entityUri) {
            if (historyEvent) {
                setIsLoading(true);
                var entityOptions = addGetEntityMaskingOptions(metadata, { showMasking: showMasking });
                safePromise(Promise.all([
                    getEntityTimeSlice(entityUri, aStamp, entityOptions),
                    bStamp && bStamp !== 1
                        ? getEntityTimeSlice(entityUri, bStamp, entityOptions)
                        : Promise.resolve(null)
                ]))
                    .then(function (_a) {
                    var aEntity = _a[0], bEntity = _a[1];
                    setHistorySlice({ aEntity: aEntity, bEntity: bEntity });
                })
                    .catch(function (e) {
                    console.warn('Failed to load entity slice', e);
                })
                    .finally(function () {
                    setIsLoading(false);
                });
            }
            else {
                safePromise(Promise.resolve());
                setIsLoading(false);
            }
        }
    }, [aStamp, bStamp, entityUri, showMasking]);
    return { isLoading: isLoading, historySlice: historySlice };
};
