import { ascend, assocPath, path, prop, curry, useWith } from 'ramda';
import { getLookupLabel } from '@reltio/mdm-sdk';
var LOOKUP_URI_SEPARATOR = '.';
var splitOnce = curry(function (separator, string) {
    var _a = string.split(separator), first = _a[0], other = _a.slice(1);
    return [first, other.join(separator)];
});
// eslint-disable-next-line react-hooks/rules-of-hooks
var getLookupByUri = useWith(path, [splitOnce(LOOKUP_URI_SEPARATOR)]);
var byLabel = ascend(prop('label'));
export var buildLookupEntries = function (lookupTypeCode, lookups) {
    var getLookupPath = function (uri) {
        var parent = (getLookupByUri(uri, lookups) || {}).parent;
        return parent ? getLookupPath(parent).concat(uri) : [uri];
    };
    var buildEntry = function (_a) {
        var uri = _a[0], value = _a[1];
        var lookup = getLookupByUri(uri, lookups);
        var _b = splitOnce(LOOKUP_URI_SEPARATOR, uri), code = _b[1];
        var label = getLookupLabel(code, lookup === null || lookup === void 0 ? void 0 : lookup.displayName);
        return lookup === value ? { label: label, value: code } : { label: label, values: buildEntries(value) };
    };
    var buildEntries = function (value) { return Object.entries(value).map(buildEntry).sort(byLabel); };
    var hierarchy = Object.entries(lookups[lookupTypeCode] || []).reduce(function (acc, _a) {
        var code = _a[0], value = _a[1];
        return assocPath(getLookupPath("".concat(lookupTypeCode).concat(LOOKUP_URI_SEPARATOR).concat(code)), value, acc);
    }, {});
    return buildEntries(hierarchy);
};
