"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useHistorySlice = 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 useHistorySlice = function (_a) {
    var entity = _a.entity, historyEvent = _a.historyEvent;
    var _b = (0, react_1.useState)(false), isLoading = _b[0], setIsLoading = _b[1];
    var setHistorySlice = (0, MdmModuleContext_1.useMdmAction)('setHistorySlice');
    var clearHistoryEvent = (0, MdmModuleContext_1.useMdmAction)('clearHistoryEvent');
    var metadata = (0, MdmModuleContext_1.useMdmMetadata)();
    var historySlice = (0, MdmModuleContext_1.useMdmHistorySlice)();
    var safePromise = (0, useSafePromise_1.useSafePromise)();
    var mode = (0, MdmModuleContext_1.useMdmMode)();
    var showMasking = (0, MdmModuleContext_1.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);
    (0, react_1.useEffect)(function () {
        if ((0, mdm_sdk_1.isEditableMode)(mode) && entityUri) {
            safePromise(Promise.resolve());
            clearHistoryEvent();
            setIsLoading(false);
        }
    }, [mode, entityUri]);
    (0, react_1.useEffect)(function () {
        if (entityUri) {
            if (historyEvent) {
                setIsLoading(true);
                var entityOptions = (0, mdm_sdk_1.addGetEntityMaskingOptions)(metadata, { showMasking: showMasking });
                safePromise(Promise.all([
                    (0, mdm_sdk_1.getEntityTimeSlice)(entityUri, aStamp, entityOptions),
                    bStamp && bStamp !== 1
                        ? (0, mdm_sdk_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 };
};
exports.useHistorySlice = useHistorySlice;
