"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLookupsResolver = void 0;
var react_1 = require("react");
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var isUnresolvedLookup = function (lookupValue) { return lookupValue && lookupValue.lookupCode && !lookupValue.value; };
var isResolvedLookupCode = (0, ramda_1.curry)(function (resolvedValues, lookupCode) {
    return (0, ramda_1.hasPath)([lookupCode, 'displayName'], resolvedValues);
});
var useLookupsResolver = function (_a) {
    var lookups = _a.lookups, resolvedValues = _a.resolvedValues, resolveLookups = _a.resolveLookups, onLookupsResolve = _a.onLookupsResolve;
    var _b = (0, react_1.useState)([]), requestedCodes = _b[0], setRequestedCodes = _b[1];
    (0, react_1.useEffect)(function () {
        var _a = (0, ramda_1.pipe)(mdm_sdk_1.wrapInArrayIfNeeded, (0, ramda_1.filter)(isUnresolvedLookup), (0, ramda_1.map)((0, ramda_1.prop)('lookupCode')), (0, ramda_1.partition)(isResolvedLookupCode(resolvedValues)))(lookups), resolvedCodes = _a[0], codesToResolve = _a[1];
        if (resolvedCodes.length > 0) {
            var resolvedLookups = resolvedCodes.map(function (lookupCode) { return ({
                lookupCode: lookupCode,
                value: resolvedValues[lookupCode].displayName
            }); });
            onLookupsResolve(resolvedLookups);
        }
        var unrequestedCodes = codesToResolve.filter(function (code) { return !requestedCodes.includes(code); });
        if (unrequestedCodes.length > 0) {
            setRequestedCodes((0, ramda_1.pipe)((0, ramda_1.concat)(unrequestedCodes), ramda_1.uniq));
            resolveLookups(unrequestedCodes);
        }
    }, [lookups, resolvedValues]); // eslint-disable-line
};
exports.useLookupsResolver = useLookupsResolver;
