"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDependentLookupEditorContext = exports.buildMissedParentsMessage = exports.fromCache = void 0;
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var DLEditorContextCache = {};
var fromCache = function (valueUri, context) {
    var cachedContext = DLEditorContextCache[valueUri];
    if ((0, ramda_1.equals)(context, cachedContext)) {
        return cachedContext;
    }
    else {
        if ((0, ramda_1.equals)(cachedContext === null || cachedContext === void 0 ? void 0 : cachedContext.parents, context.parents)) {
            context.parents = cachedContext.parents;
        }
        DLEditorContextCache[valueUri] = context;
        return context;
    }
};
exports.fromCache = fromCache;
var joinWords = function (words) {
    return words.reduce(function (result, word, i) { return [result, word].join(i === words.length - 1 ? " ".concat(ui_i18n_1.default.text('and'), " ") : ', '); });
};
var buildMissedParentsMessage = function (missedAttributeTypes) {
    if (!missedAttributeTypes.length)
        return '';
    return ui_i18n_1.default.text('Please select value for ${labels} ${attributes}.', {
        labels: joinWords(missedAttributeTypes.map((0, ramda_1.pipe)((0, ramda_1.prop)('label'), function (label) { return "'".concat(label, "'"); }))),
        attributes: missedAttributeTypes.length === 1 ? ui_i18n_1.default.text('attribute') : ui_i18n_1.default.text('attributes')
    });
};
exports.buildMissedParentsMessage = buildMissedParentsMessage;
var getTypesMapKey = function (parent) { return "".concat(parent.type, "_").concat((0, mdm_sdk_1.getParentUri)(parent.uri)); };
var getParents = function (_a) {
    var _b;
    var dependentLookups = _a.dependentLookups, metadata = _a.metadata, modifiedEntities = _a.modifiedEntities, entityUri = _a.entityUri, relations = _a.relations, node = _a.node, valueUri = _a.valueUri, hiddenAttributes = _a.hiddenAttributes;
    var parentNodesValues = node.parents
        .filter(function (type) { return !hiddenAttributes.includes(type); })
        .flatMap(function (type) {
        var parentNode = (0, mdm_sdk_1.getDependentLookupsStructureNode)(dependentLookups, type);
        return parentNode.values.map(function (value) { return (__assign(__assign({}, value), { type: type, dependentLookupCode: parentNode.attrType.dependentLookupCode })); });
    });
    var connections = (0, mdm_sdk_1.getAllRelationsToAddAndEdit)(relations);
    var ownParentNodesValues = (0, mdm_sdk_1.filterRelatedParentValuesForDependentLookupValueUri)({
        parentValues: parentNodesValues,
        valueUri: valueUri,
        entityUri: entityUri,
        modifiedEntities: modifiedEntities,
        connections: connections
    });
    var possibleParentBaseTypeUris = (0, ramda_1.pipe)(mdm_sdk_1.getAttributeValuePath, (0, ramda_1.defaultTo)([]), (0, ramda_1.map)((0, ramda_1.pipe)((0, ramda_1.path)(['valueType', 'uri']), mdm_sdk_1.getBaseUri)), (0, ramda_1.prepend)((_b = modifiedEntities[entityUri]) === null || _b === void 0 ? void 0 : _b.type), (0, ramda_1.reject)(ramda_1.isNil), ramda_1.uniq)({ entityUri: entityUri, entitiesMap: modifiedEntities, connections: connections, metadata: metadata }, valueUri);
    var neededParentsAttributeTypes = node.parents
        .filter(function (type) { return !hiddenAttributes.includes(type); })
        .filter(function (typeUri) { return possibleParentBaseTypeUris.some((0, mdm_sdk_1.areOneHierarchyUris)(typeUri)); })
        .map(function (typeUri) {
        var parentNode = (0, mdm_sdk_1.getDependentLookupsStructureNode)(dependentLookups, typeUri);
        return parentNode.attrType;
    });
    var missedParentsAttributeTypes = neededParentsAttributeTypes.filter(function (attrType) { return !ownParentNodesValues.some(function (_a) {
        var type = _a.type, value = _a.value;
        return value && type === attrType.uri;
    }); });
    var parents = Object.values(ownParentNodesValues.reduce(function (typesMap, parent) {
        var _a;
        var _b;
        var key = getTypesMapKey(parent);
        return __assign(__assign({}, typesMap), (_a = {}, _a[key] = {
            type: parent.dependentLookupCode,
            codeValues: (0, ramda_1.uniq)(__spreadArray([parent.value], (((_b = typesMap[key]) === null || _b === void 0 ? void 0 : _b.codeValues) || []), true))
                .filter(Boolean)
                .sort()
        }, _a));
    }, {})).filter(function (item) { return !!item.codeValues.length; });
    return { parents: parents, missedParentsAttributeTypes: missedParentsAttributeTypes };
};
var getDependentLookupEditorContext = function (_a) {
    var dependentLookups = _a.dependentLookups, metadata = _a.metadata, modifiedEntities = _a.modifiedEntities, entityUri = _a.entityUri, relations = _a.relations, attributeValue = _a.attributeValue, attributeType = _a.attributeType, _b = _a.hiddenAttributes, hiddenAttributes = _b === void 0 ? [] : _b;
    if (!(0, mdm_sdk_1.isDependentLookupAttrType)(attributeType) || hiddenAttributes.includes(attributeType.uri)) {
        return null;
    }
    var attributeTypeUri = attributeType.uri;
    var node = (0, mdm_sdk_1.getDependentLookupsStructureNode)(dependentLookups, attributeTypeUri);
    if (node) {
        var valueUri = attributeValue.uri;
        var _c = getParents({
            dependentLookups: dependentLookups,
            metadata: metadata,
            modifiedEntities: modifiedEntities,
            entityUri: entityUri,
            relations: relations,
            valueUri: valueUri,
            node: node,
            hiddenAttributes: hiddenAttributes
        }), parents = _c.parents, missedParentsAttributeTypes = _c.missedParentsAttributeTypes;
        var _d = ((0, mdm_sdk_1.getDependentLookupEditorState)(dependentLookups, valueUri) || {}).isBlocked, isBlocked = _d === void 0 ? false : _d;
        var missedParentsMessage = (0, exports.buildMissedParentsMessage)(missedParentsAttributeTypes);
        var isEmptyValue = !(attributeValue === null || attributeValue === void 0 ? void 0 : attributeValue.lookupCode) && !(attributeValue === null || attributeValue === void 0 ? void 0 : attributeValue.value);
        var placeholder = (isEmptyValue && isBlocked && ui_i18n_1.default.text('Populating values...')) ||
            (isEmptyValue && missedParentsMessage) ||
            '';
        var context = {
            parents: missedParentsMessage ? null : parents,
            disabled: (!!missedParentsMessage && isEmptyValue) || isBlocked,
            placeholder: placeholder
        };
        if (placeholder) {
            context.value = null;
        }
        return (0, exports.fromCache)(valueUri, context);
    }
};
exports.getDependentLookupEditorContext = getDependentLookupEditorContext;
