"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildLookupEntries = void 0;
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var LOOKUP_URI_SEPARATOR = '.';
var splitOnce = (0, ramda_1.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 = (0, ramda_1.useWith)(ramda_1.path, [splitOnce(LOOKUP_URI_SEPARATOR)]);
var byLabel = (0, ramda_1.ascend)((0, ramda_1.prop)('label'));
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 = (0, mdm_sdk_1.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 (0, ramda_1.assocPath)(getLookupPath("".concat(lookupTypeCode).concat(LOOKUP_URI_SEPARATOR).concat(code)), value, acc);
    }, {});
    return buildEntries(hierarchy);
};
exports.buildLookupEntries = buildLookupEntries;
