"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);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useHistory = void 0;
var react_1 = require("react");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var filters_1 = require("../helpers/filters");
var useSafePromise_1 = require("../../../hooks/useSafePromise");
var constants_1 = require("../constants");
var MAX_HISTORY_ROWS = 32;
var useHistory = function (_a) {
    var entity = _a.entity, enabled = _a.enabled;
    var _b = (0, react_1.useState)(constants_1.DEFAULT_HISTORY_FILTER), historyFilter = _b[0], setHistoryFilter = _b[1];
    var _c = (0, react_1.useState)(0), historyPage = _c[0], setHistoryPage = _c[1];
    var historyFilterString = (0, react_1.useMemo)(function () { return (0, filters_1.buildHistoryFilterString)(historyFilter); }, [historyFilter]);
    var _d = (0, react_1.useState)(null), historicUris = _d[0], setHistoricUris = _d[1];
    var _e = (0, react_1.useState)(null), historyWithTotal = _e[0], setHistoryWithTotal = _e[1];
    var _f = (0, react_1.useState)(false), isLoading = _f[0], setIsLoading = _f[1];
    var safePromise = (0, useSafePromise_1.useSafePromise)();
    var entityUri = entity === null || entity === void 0 ? void 0 : entity.uri;
    var options = { max: MAX_HISTORY_ROWS, order: 'desc' };
    var showAll = (0, mdm_sdk_1.isEmptyValue)(historyFilter === null || historyFilter === void 0 ? void 0 : historyFilter.attributes) || undefined;
    var loadHistoryWithTotal = function () {
        setIsLoading(true);
        return safePromise((0, mdm_sdk_1.getHistoryWithTotal)(__assign({ entityUri: entityUri, historicUris: historicUris, filter: historyFilterString, showAll: showAll }, options)))
            .then(setHistoryWithTotal)
            .catch(function (e) {
            console.warn('Failed to load history data', e);
            setHistoryWithTotal(null);
        })
            .finally(function () {
            setIsLoading(false);
        });
    };
    (0, react_1.useEffect)(function () {
        if (entityUri && enabled) {
            loadHistoryWithTotal();
        }
    }, [historyFilterString, showAll, historicUris]);
    var loadHistoricUris = function () {
        setIsLoading(true);
        return safePromise((0, mdm_sdk_1.getHistoricUris)({ entityUri: entityUri }))
            .then(function (historicUris) {
            setHistoricUris(historicUris);
        })
            .catch(function (e) {
            console.warn('Failed to load history data', e);
            setHistoricUris(null);
        })
            .finally(function () {
            setIsLoading(false);
        });
    };
    (0, react_1.useEffect)(function () {
        if (entityUri && enabled) {
            loadHistoricUris();
            setHistoryPage(0);
            setHistoryWithTotal(null);
        }
    }, [entityUri, entity === null || entity === void 0 ? void 0 : entity.updatedTime, enabled]);
    var loadMore = (0, react_1.useCallback)(function (offset) {
        if (entityUri && historicUris && enabled) {
            setIsLoading(true);
            safePromise((0, mdm_sdk_1.getHistoryWithTotal)(__assign({ entityUri: entityUri, historicUris: historicUris, filter: historyFilterString, showAll: showAll, offset: offset }, options)))
                .then(function (results) {
                setHistoryWithTotal(function (prev) { return (__assign(__assign({}, prev), { changes: __spreadArray(__spreadArray([], (prev.changes || []), true), (results.changes || []), true) })); });
            })
                .catch(function (e) {
                console.warn('Failed to load history data', e);
            })
                .finally(function () {
                setIsLoading(false);
            });
        }
    }, [historicUris, historyFilterString, enabled]);
    var canLoadMore = (0, react_1.useMemo)(function () { return (historyPage + 1) * MAX_HISTORY_ROWS < (historyWithTotal === null || historyWithTotal === void 0 ? void 0 : historyWithTotal.total); }, [historyWithTotal, historyPage]);
    var onApplyFilter = (0, react_1.useCallback)(function (filter) {
        setHistoryPage(0);
        setHistoryFilter(filter);
    }, []);
    var onClearFilter = (0, react_1.useCallback)(function () {
        onApplyFilter(__assign({}, constants_1.DEFAULT_HISTORY_FILTER));
    }, []);
    var onLoadMore = (0, react_1.useCallback)(function () {
        if (!canLoadMore)
            return;
        loadMore((historyPage + 1) * MAX_HISTORY_ROWS);
        setHistoryPage(historyPage + 1);
    }, [loadMore, historyPage, canLoadMore]);
    return {
        isLoading: isLoading,
        canLoadMore: canLoadMore,
        onLoadMore: onLoadMore,
        onApplyFilter: onApplyFilter,
        onClearFilter: onClearFilter,
        historicUris: historicUris,
        historyWithTotal: historyWithTotal,
        historyFilter: historyFilter
    };
};
exports.useHistory = useHistory;
