import { useEffect, useState } from 'react';
import { curry, filter, hasPath, map, partition, pipe, prop, concat, uniq } from 'ramda';
import { wrapInArrayIfNeeded } from '@reltio/mdm-sdk';
var isUnresolvedLookup = function (lookupValue) { return lookupValue && lookupValue.lookupCode && !lookupValue.value; };
var isResolvedLookupCode = curry(function (resolvedValues, lookupCode) {
    return hasPath([lookupCode, 'displayName'], resolvedValues);
});
export var useLookupsResolver = function (_a) {
    var lookups = _a.lookups, resolvedValues = _a.resolvedValues, resolveLookups = _a.resolveLookups, onLookupsResolve = _a.onLookupsResolve;
    var _b = useState([]), requestedCodes = _b[0], setRequestedCodes = _b[1];
    useEffect(function () {
        var _a = pipe(wrapInArrayIfNeeded, filter(isUnresolvedLookup), map(prop('lookupCode')), 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(pipe(concat(unrequestedCodes), uniq));
            resolveLookups(unrequestedCodes);
        }
    }, [lookups, resolvedValues]); // eslint-disable-line
};
