"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMergeAllRequest = void 0;
var react_1 = require("react");
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var useIsMountedRef_1 = require("../useIsMountedRef");
var helpers_1 = require("./helpers");
var MdmModuleContext_1 = require("../../contexts/MdmModuleContext");
var useMergeAllRequest = function (_a) {
    var entities = _a.entities, entity = _a.entity, onFinishRequest = _a.onFinishRequest, onStartRequest = _a.onStartRequest, onSuccess = _a.onSuccess, _b = _a.onError, onError = _b === void 0 ? ramda_1.identity : _b;
    var isMountedRef = (0, useIsMountedRef_1.useIsMountedRef)();
    var _c = (0, react_1.useState)(false), isPending = _c[0], setIsPending = _c[1];
    var updateSearchNavigationDataOnMerge = (0, MdmModuleContext_1.useMdmAction)('updateSearchNavigationDataOnMerge');
    var tenant = (0, MdmModuleContext_1.useMdmTenant)();
    var dtssPath = (0, MdmModuleContext_1.useMdmDtssPath)();
    var sendMergeAllRequest = (0, react_1.useCallback)(function () {
        onStartRequest === null || onStartRequest === void 0 ? void 0 : onStartRequest();
        setIsPending(true);
        var params = { dtssPath: dtssPath, customerTenant: tenant, entity: entity, entities: entities };
        ((0, mdm_sdk_1.isDataTenantEntity)(entity)
            ? (0, mdm_sdk_1.mergeDataTenantEntity)(params)
            : (0, mdm_sdk_1.mergeCustomerTenantEntityWithMixedEntities)(params))
            .then(function (responses) {
            onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess();
            var uris = (0, helpers_1.getWinnerLosersUrisFromMergeResponses)(entity, entities, responses);
            if (uris) {
                var winnerUri = uris.winnerUri, losersUris = uris.losersUris;
                updateSearchNavigationDataOnMerge({ winnerUri: winnerUri, losersUris: losersUris });
            }
        })
            .catch(onError)
            .finally(function () {
            onFinishRequest === null || onFinishRequest === void 0 ? void 0 : onFinishRequest();
            if (isMountedRef.current)
                setIsPending(false);
        });
    }, [
        dtssPath,
        entities,
        entity,
        onError,
        onFinishRequest,
        onStartRequest,
        onSuccess,
        tenant,
        updateSearchNavigationDataOnMerge
    ]);
    return { isPending: isPending, sendMergeAllRequest: sendMergeAllRequest };
};
exports.useMergeAllRequest = useMergeAllRequest;
