"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.usePivotingDataLoader = exports.MAX_ENTITIES_PIVOTING_TOOLTIP = void 0;
var react_1 = require("react");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var MdmModuleContext_1 = require("../../contexts/MdmModuleContext");
var useSafePromise_1 = require("../useSafePromise");
exports.MAX_ENTITIES_PIVOTING_TOOLTIP = 6;
var usePivotingDataLoader = function (_a) {
    var value = _a.value, attributeType = _a.attributeType, configEntityType = _a.entityType;
    var _b = (0, react_1.useState)([]), entities = _b[0], setEntities = _b[1];
    var _c = (0, react_1.useState)(0), total = _c[0], setTotal = _c[1];
    var safePromise = (0, useSafePromise_1.useSafePromise)();
    var entity = (0, MdmModuleContext_1.useMdmEntity)();
    var globalSearchRequestOptions = (0, MdmModuleContext_1.useMdmGlobalSearchRequestOptions)();
    var entityType = configEntityType || (entity === null || entity === void 0 ? void 0 : entity.type);
    var filters = (0, react_1.useMemo)(function () { return (0, mdm_sdk_1.convertPivotingValueToSearchFilters)({ value: value, attributeType: attributeType, entityType: entityType }); }, [attributeType, entityType, value]);
    var options = (0, react_1.useMemo)(function () { return (__assign({ max: exports.MAX_ENTITIES_PIVOTING_TOOLTIP, sort: 'label' }, (globalSearchRequestOptions || {}))); }, [globalSearchRequestOptions]);
    var loadPivotingData = (0, react_1.useCallback)(function () {
        safePromise(Promise.all([(0, mdm_sdk_1.getFilteredEntities)({ filters: filters, options: options }), (0, mdm_sdk_1.getTotals)({ filters: filters, options: options })]))
            .then(function (results) {
            var entities = results[0], total = results[1].total;
            setEntities(Array.isArray(entities) ? entities : []);
            setTotal(total);
        })
            .catch(function (error) {
            console.warn("Can't load entities or total for pivoting data", error);
            setEntities([]);
            setTotal(0);
        });
    }, [filters, options, safePromise]);
    return { entities: entities, total: total, loadPivotingData: loadPivotingData };
};
exports.usePivotingDataLoader = usePivotingDataLoader;
