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);
};
import { useCallback, useState, useMemo } from 'react';
import { convertPivotingValueToSearchFilters, getFilteredEntities, getTotals } from '@reltio/mdm-sdk';
import { useMdmEntity, useMdmGlobalSearchRequestOptions } from '../../contexts/MdmModuleContext';
import { useSafePromise } from '../useSafePromise';
export var MAX_ENTITIES_PIVOTING_TOOLTIP = 6;
export var usePivotingDataLoader = function (_a) {
    var value = _a.value, attributeType = _a.attributeType, configEntityType = _a.entityType;
    var _b = useState([]), entities = _b[0], setEntities = _b[1];
    var _c = useState(0), total = _c[0], setTotal = _c[1];
    var safePromise = useSafePromise();
    var entity = useMdmEntity();
    var globalSearchRequestOptions = useMdmGlobalSearchRequestOptions();
    var entityType = configEntityType || (entity === null || entity === void 0 ? void 0 : entity.type);
    var filters = useMemo(function () { return convertPivotingValueToSearchFilters({ value: value, attributeType: attributeType, entityType: entityType }); }, [attributeType, entityType, value]);
    var options = useMemo(function () { return (__assign({ max: MAX_ENTITIES_PIVOTING_TOOLTIP, sort: 'label' }, (globalSearchRequestOptions || {}))); }, [globalSearchRequestOptions]);
    var loadPivotingData = useCallback(function () {
        safePromise(Promise.all([getFilteredEntities({ filters: filters, options: options }), 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 };
};
