"use strict";
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.sortByPinIgnorePriority = exports.getBasicTableRowsData = exports.getBasicTableColumnsData = exports.getWinnerCrosswalks = exports.getFallbackLabels = exports.collectRuleNames = exports.countAttributeValues = exports.DEFAULT_VISIBLE_COLUMNS = exports.COLUMNS_DATA = void 0;
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var HeadCellRenderer_1 = require("./components/HeadCellRenderer");
var AttributesHeadCellRenderer_1 = require("./components/AttributesHeadCellRenderer");
var DefaultCellValueRenderer_1 = require("./components/DefaultCellValueRenderer");
var AttributeValuesRenderer_1 = require("./components/AttributeValuesRenderer");
var OvValuesRenderer_1 = require("./components/OvValuesRenderer");
var CountRenderer_1 = require("./components/CountRenderer");
var RuleTypeRenderer_1 = require("./components/RuleTypeRenderer");
var WinnerSourcesRenderer_1 = require("./components/WinnerSourcesRenderer");
var types_1 = require("./types");
exports.COLUMNS_DATA = [
    {
        id: 'ovValues',
        get label() {
            return ui_i18n_1.default.text('Attributes & OV');
        },
        hideable: false,
        initialWidth: 360,
        minWidth: 250
    },
    {
        id: 'winnerSources',
        get label() {
            return ui_i18n_1.default.text('Winner source systems');
        },
        initialWidth: 220
    },
    {
        id: 'ruleType',
        get label() {
            return ui_i18n_1.default.text('Rule type');
        },
        initialWidth: 200
    },
    {
        id: 'count',
        get label() {
            return ui_i18n_1.default.text('Count');
        },
        initialWidth: 80,
        minWidth: 80
    },
    {
        id: 'values',
        get label() {
            return ui_i18n_1.default.text('Attribute values');
        },
        hideable: false
    }
];
var isOvValue = function (value) { return (0, mdm_sdk_1.isOv)(value) && !(0, mdm_sdk_1.isTempUri)(value.uri); };
exports.DEFAULT_VISIBLE_COLUMNS = ['ovValues', 'ruleType', 'values'];
var getCellValueRenderer = function (columnId) {
    switch (columnId) {
        case 'ovValues':
            return OvValuesRenderer_1.OvValuesRenderer;
        case 'values':
            return AttributeValuesRenderer_1.AttributeValuesRenderer;
        case 'count':
            return CountRenderer_1.CountRenderer;
        case 'ruleType':
            return RuleTypeRenderer_1.RuleTypeRenderer;
        case 'winnerSources':
            return WinnerSourcesRenderer_1.WinnerSourcesRenderer;
        default:
            return DefaultCellValueRenderer_1.DefaultCellValueRenderer;
    }
};
var countAttributeValues = function (type, values, crosswalksMap) {
    if (values === void 0) { values = []; }
    switch (type) {
        case mdm_sdk_1.DataTypes.TYPE_REFERENCE:
        case mdm_sdk_1.DataTypes.TYPE_NESTED:
        case mdm_sdk_1.DataTypes.TYPE_IMAGE:
            return values.length;
        default:
            return values.reduce(function (acc, value) { return acc + (0, ramda_1.pathOr)(0, [value.uri, 'length'], crosswalksMap); }, 0);
    }
};
exports.countAttributeValues = countAttributeValues;
var isSourceSystemRule = function (ruleType) {
    return (ruleType === null || ruleType === void 0 ? void 0 : ruleType.uri) === 'configuration/survivorshipStrategies/SRC_SYS';
};
var isOtherAttributeWinnerRule = function (ruleType) {
    return (ruleType === null || ruleType === void 0 ? void 0 : ruleType.uri) === 'configuration/survivorshipStrategies/OtherAttributeWinnerCrosswalk';
};
var isMinMaxValueRule = function (ruleType) {
    return (ruleType === null || ruleType === void 0 ? void 0 : ruleType.uri) === 'configuration/survivorshipStrategies/MinValue' ||
        (ruleType === null || ruleType === void 0 ? void 0 : ruleType.uri) === 'configuration/survivorshipStrategies/MaxValue';
};
var getSourcesUriOrderFromMetadata = (0, ramda_1.pipe)(mdm_sdk_1.getCrosswalksTypes, (0, ramda_1.sortWith)([(0, ramda_1.descend)((0, ramda_1.propOr)(-1, 'priority'))]), (0, ramda_1.map)((0, ramda_1.prop)('uri')));
var fixReferencedAttributeUri = (0, ramda_1.curry)(function (parentType, attrTypeUri) {
    if ((0, mdm_sdk_1.isReference)(parentType) && attrTypeUri) {
        var referencedAttrUri = (0, ramda_1.pipe)(mdm_sdk_1.getReferencedAttrTypeUrisFromAttrType, (0, ramda_1.find)(function (uri) { return uri.slice((0, mdm_sdk_1.getBaseUri)(uri).length) === attrTypeUri.slice(parentType.uri.length); }))(parentType);
        return referencedAttrUri || attrTypeUri;
    }
    else {
        return attrTypeUri;
    }
});
var collectRuleNames = function (rule) {
    if (!rule) {
        return [];
    }
    if (typeof rule === 'string') {
        return [rule];
    }
    var entries = Object.entries(rule);
    return entries.flatMap(function (_a) {
        var key = _a[0], value = _a[1];
        return __spreadArray([key], value.flatMap(exports.collectRuleNames), true);
    });
};
exports.collectRuleNames = collectRuleNames;
var getFallbackLabels = function (metadata, ovDetails) {
    if ((ovDetails === null || ovDetails === void 0 ? void 0 : ovDetails.participationStatus) && ovDetails.participationStatus !== mdm_sdk_1.ParticipationStatus.Strategy) {
        return [];
    }
    var appliedRules = ovDetails === null || ovDetails === void 0 ? void 0 : ovDetails.appliedSurvivorshipRules;
    var rules = (0, exports.collectRuleNames)(appliedRules);
    if (rules.length <= 1) {
        return [];
    }
    return rules.map(function (uri) { var _a; return ((_a = (0, mdm_sdk_1.getSurvivorshipStrategy)(metadata, uri)) === null || _a === void 0 ? void 0 : _a.label) || uri; });
};
exports.getFallbackLabels = getFallbackLabels;
var createRuleTypeData = function (_a) {
    var metadata = _a.metadata, strategy = _a.strategy, mapping = _a.mapping, attributeType = _a.attributeType, currentSurvivorshipGroup = _a.currentSurvivorshipGroup;
    var fixUri = fixReferencedAttributeUri(attributeType);
    var primaryAttributeUri = isOtherAttributeWinnerRule(strategy) ? fixUri(mapping === null || mapping === void 0 ? void 0 : mapping.primaryAttributeUri) : undefined;
    var comparisonAttributeUri = (0, mdm_sdk_1.isComplexAttribute)(attributeType) && isMinMaxValueRule(strategy)
        ? fixUri(mapping === null || mapping === void 0 ? void 0 : mapping.comparisonAttributeUri)
        : undefined;
    var sourcesUriOrder = isSourceSystemRule(strategy)
        ? (0, ramda_1.uniq)(__spreadArray(__spreadArray(__spreadArray([], ((mapping === null || mapping === void 0 ? void 0 : mapping.sourcesUriOrder) || []), true), ((currentSurvivorshipGroup === null || currentSurvivorshipGroup === void 0 ? void 0 : currentSurvivorshipGroup.sourcesUriOrder) || []), true), getSourcesUriOrderFromMetadata(metadata), true))
        : undefined;
    return {
        type: types_1.RuleItemType.Rule,
        data: {
            strategy: strategy,
            primaryAttributeUri: primaryAttributeUri,
            comparisonAttributeUri: comparisonAttributeUri,
            sourcesUriOrder: sourcesUriOrder
        }
    };
};
var mapAttributeToRuleType = function (_a) {
    var metadata = _a.metadata, attributeType = _a.attributeType, attributeValue = _a.attributeValue, mapping = _a.mapping, currentSurvivorshipGroup = _a.currentSurvivorshipGroup;
    var ovDetails = attributeValue.ovDetails;
    if (!ovDetails) {
        return null;
    }
    if (ovDetails.participationStatus === mdm_sdk_1.ParticipationStatus.Strategy) {
        var appliedRules = (0, exports.collectRuleNames)(ovDetails.appliedSurvivorshipRules);
        var lastRule = (0, mdm_sdk_1.getSurvivorshipStrategy)(metadata, (0, ramda_1.last)(appliedRules));
        return lastRule
            ? createRuleTypeData({
                metadata: metadata,
                strategy: lastRule,
                mapping: mapping,
                attributeType: attributeType,
                currentSurvivorshipGroup: currentSurvivorshipGroup
            })
            : null;
    }
    return {
        type: types_1.RuleItemType.Status,
        data: ovDetails.participationStatus
    };
};
var getOvAttributeValues = function (attributeValues) {
    if (!attributeValues) {
        return [];
    }
    return (0, ramda_1.pipe)((0, ramda_1.filter)(isOvValue), (0, ramda_1.filter)((0, ramda_1.has)('ovDetails')), (0, ramda_1.map)((0, ramda_1.pick)(['uri', 'value', 'ovDetails'])))(attributeValues);
};
var getRuleTypeValues = function (_a) {
    var _b, _c;
    var metadata = _a.metadata, attributeType = _a.attributeType, parentTypeUri = _a.parentTypeUri, attributeValues = _a.attributeValues, activeSurvivorshipGroupUri = _a.activeSurvivorshipGroupUri;
    var parentType = __spreadArray(__spreadArray([], metadata.entityTypes, true), (metadata.relationTypes || []), true).find((0, ramda_1.propEq)('uri', parentTypeUri));
    var survivorshipGroups = (_b = parentType === null || parentType === void 0 ? void 0 : parentType.survivorshipGroups) !== null && _b !== void 0 ? _b : [];
    var currentSurvivorshipGroup = (activeSurvivorshipGroupUri && survivorshipGroups.find((0, ramda_1.propEq)('uri', activeSurvivorshipGroupUri))) ||
        survivorshipGroups.find((0, ramda_1.propEq)('default', true));
    var mapping = (_c = currentSurvivorshipGroup === null || currentSurvivorshipGroup === void 0 ? void 0 : currentSurvivorshipGroup.mapping) === null || _c === void 0 ? void 0 : _c.find((0, ramda_1.propEq)('attribute', attributeType.uri));
    var defaultSurvivorshipStrategy = (0, mdm_sdk_1.getSurvivorshipStrategy)(metadata, mapping === null || mapping === void 0 ? void 0 : mapping.survivorshipStrategy) || (0, mdm_sdk_1.getDefaultSurvivorshipStrategy)(metadata);
    var defaultRuleType = createRuleTypeData({
        metadata: metadata,
        strategy: defaultSurvivorshipStrategy,
        mapping: mapping,
        attributeType: attributeType,
        currentSurvivorshipGroup: currentSurvivorshipGroup
    });
    var ovAttributeValues = getOvAttributeValues(attributeValues);
    var getRuleTypeData = function (attrType, attrValue) {
        var _a, _b;
        if (!(attrValue === null || attrValue === void 0 ? void 0 : attrValue.ovDetails)) {
            return defaultRuleType;
        }
        var mappingForAttr = attrType.uri === attributeType.uri
            ? mapping
            : (_a = currentSurvivorshipGroup === null || currentSurvivorshipGroup === void 0 ? void 0 : currentSurvivorshipGroup.mapping) === null || _a === void 0 ? void 0 : _a.find((0, ramda_1.propEq)('attribute', attrType.uri));
        return ((_b = mapAttributeToRuleType({
            metadata: metadata,
            attributeType: attrType,
            attributeValue: attrValue,
            mapping: mappingForAttr,
            currentSurvivorshipGroup: currentSurvivorshipGroup
        })) !== null && _b !== void 0 ? _b : defaultRuleType);
    };
    if (ovAttributeValues.length > 0) {
        return {
            attributeType: attributeType,
            attributeValues: ovAttributeValues,
            getRuleTypeData: getRuleTypeData
        };
    }
    return {
        attributeType: attributeType,
        attributeValues: [],
        getRuleTypeData: getRuleTypeData
    };
};
var getWinnerCrosswalks = function (attributeValues, crosswalksMap) {
    if (attributeValues === void 0) { attributeValues = []; }
    return (0, ramda_1.pipe)((0, ramda_1.filter)(isOvValue), (0, ramda_1.chain)(function (value) {
        return (0, ramda_1.pipe)((0, ramda_1.pickBy)(function (_, attrUri) {
            var isInHierarchy = (0, mdm_sdk_1.areOneHierarchyUris)(attrUri, value.uri);
            var subAttrUriSuffix = isInHierarchy ? attrUri.slice(value.uri.length + 1) : '';
            var subAttrValue = subAttrUriSuffix &&
                (0, mdm_sdk_1.findValueInAttributesByUriSuffix)(value.value, subAttrUriSuffix);
            return isInHierarchy && (!subAttrValue || isOvValue(subAttrValue));
        }), ramda_1.values, ramda_1.flatten)(crosswalksMap);
    }), (0, ramda_1.uniqBy)((0, ramda_1.prop)('uri')))(attributeValues);
};
exports.getWinnerCrosswalks = getWinnerCrosswalks;
exports.getBasicTableColumnsData = (0, ramda_1.map)(function (_a) {
    var id = _a.id, label = _a.label, initialWidth = _a.initialWidth, minWidth = _a.minWidth;
    return ({
        id: id,
        label: label,
        initialWidth: initialWidth,
        minWidth: minWidth,
        autoResize: !initialWidth,
        resizable: true,
        sortable: false,
        headCellRenderer: id === 'ovValues' ? AttributesHeadCellRenderer_1.AttributesHeadCellRenderer : HeadCellRenderer_1.HeadCellRenderer,
        rowCellValueRenderer: getCellValueRenderer(id)
    });
});
var getRowValueForColumn = function (columnId, metadata, parentTypeUri, attributeType, crosswalksMap, attributeValues, activeSurvivorshipGroupUri) {
    switch (columnId) {
        case 'ovValues':
            return {
                attributeType: attributeType,
                values: attributeValues === null || attributeValues === void 0 ? void 0 : attributeValues.filter(isOvValue)
            };
        case 'values':
            return {
                attributeType: attributeType,
                attributeValues: attributeValues,
                crosswalksMap: crosswalksMap
            };
        case 'count':
            return (0, exports.countAttributeValues)(attributeType.type, attributeValues, crosswalksMap);
        case 'ruleType':
            return getRuleTypeValues({
                metadata: metadata,
                attributeType: attributeType,
                parentTypeUri: parentTypeUri,
                attributeValues: attributeValues,
                activeSurvivorshipGroupUri: activeSurvivorshipGroupUri
            });
        case 'winnerSources':
            return { crosswalks: (0, exports.getWinnerCrosswalks)(attributeValues, crosswalksMap) };
        default:
            return null;
    }
};
var getBasicTableRowsData = function (metadata, parentTypeUri, attrTypes, columns, crosswalksMap, attributes, activeSurvivorshipGroupUri) {
    if (attrTypes === void 0) { attrTypes = []; }
    return attrTypes.map(function (attributeType) {
        var attrName = (0, mdm_sdk_1.getLastUriPart)(attributeType.uri);
        var attrValues = attributes[attrName];
        var crosswalksMapForAttribute = (0, mdm_sdk_1.isReference)(attributeType) ? crosswalksMap.relation : crosswalksMap.entity;
        return (0, ramda_1.pipe)((0, ramda_1.reduce)(function (acc, columnId) {
            return (0, ramda_1.assoc)(columnId, getRowValueForColumn(columnId, metadata, parentTypeUri, attributeType, crosswalksMapForAttribute, attrValues, activeSurvivorshipGroupUri), acc);
        }, {}), (0, ramda_1.assoc)('rawValue', attrValues))(columns);
    });
};
exports.getBasicTableRowsData = getBasicTableRowsData;
var getDisplayTier = function (v) {
    if (v.pin)
        return 0;
    if (v.ignored)
        return 2;
    return 1;
};
var sortByPinIgnorePriority = function (values) {
    return ((values && __spreadArray([], values, true)) || []).sort(function (a, b) { return getDisplayTier(a) - getDisplayTier(b); });
};
exports.sortByPinIgnorePriority = sortByPinIgnorePriority;
