"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSavedStateForEntityType = void 0;
var react_1 = require("react");
var useDidUpdateEffect_1 = require("../useDidUpdateEffect");
var useSavedStateForEntityType = function (_a) {
    var getSavedState = _a.getSavedState, saveState = _a.saveState, entityTypeUri = _a.entityTypeUri;
    var _b = (0, react_1.useState)({}), savedState = _b[0], setSavedState = _b[1];
    var _c = (0, react_1.useState)(null), changedState = _c[0], setChangedState = _c[1];
    var _d = (0, react_1.useState)(false), isLoaded = _d[0], setIsLoaded = _d[1];
    var saveChangesLocallyForPrevEntityType = function () {
        if (changedState) {
            setSavedState(__assign(__assign({}, savedState), changedState));
            setChangedState(null);
        }
    };
    (0, useDidUpdateEffect_1.useDidUpdateEffect)(saveChangesLocallyForPrevEntityType, [entityTypeUri]);
    var updateSavedState = (0, react_1.useCallback)(function (stateToSave) {
        var _a;
        if (!entityTypeUri)
            return;
        var changedState = (_a = {},
            _a[entityTypeUri] = stateToSave,
            _a);
        setChangedState(changedState);
        saveState(__assign(__assign({}, savedState), changedState));
    }, [entityTypeUri, saveState, savedState]);
    (0, react_1.useEffect)(function () {
        getSavedState()
            .then(function (savedState) {
            setSavedState(savedState || {});
        })
            .catch(function (error) {
            console.warn("Can't load saved state for entity type", error);
        })
            .finally(function () {
            setIsLoaded(true);
        });
    }, []); // eslint-disable-line react-hooks/exhaustive-deps
    return { isLoaded: isLoaded && !!entityTypeUri, savedState: savedState[entityTypeUri], updateSavedState: updateSavedState };
};
exports.useSavedStateForEntityType = useSavedStateForEntityType;
