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);
};
import { pluck, prop, uniqBy } from 'ramda';
import { findAttributeTypeByUri, findAttributeValuesByTypeUri, isComplexAttribute, isOv, getParentUri, generateUri, InputCleanseAttributeType, areOneHierarchyUris, DataTypes, isNested } from '@reltio/mdm-sdk';
var MINIMUM_NESTED_LEVEL = 1;
var MIN_SEARCH_TEXT_LEN = 3;
var SEARCH_RESULTS_LIMIT = 10;
var COUNTRIES_DELIMETER = ';';
var genAttributeValueUri = function (_a) {
    var _b;
    var attributeType = _a.attributeType, parentValueUri = _a.parentValueUri, attributeTypeUri = _a.attributeTypeUri, modifiedEntity = _a.modifiedEntity, metadata = _a.metadata, existingValues = _a.existingValues, _c = _a.hasValues, hasValues = _c === void 0 ? true : _c;
    var currentExistingValue = existingValues.find(function (_a) {
        var uri = _a.uri;
        return areOneHierarchyUris(uri, parentValueUri);
    });
    var hasExistingValues = Boolean(hasValues && currentExistingValue);
    var currentLevelUri = hasExistingValues
        ? currentExistingValue.uri
        : generateUri(parentValueUri, attributeType.name);
    if (isNested(attributeType)) {
        var subAttributes = attributeType.attributes;
        if (subAttributes === null || subAttributes === void 0 ? void 0 : subAttributes.length) {
            var subAttrubuteType = subAttributes.find(function (_a) {
                var uri = _a.uri;
                return areOneHierarchyUris(attributeTypeUri, uri);
            });
            if (subAttrubuteType) {
                return genAttributeValueUri({
                    attributeType: subAttrubuteType,
                    parentValueUri: currentLevelUri,
                    attributeTypeUri: attributeTypeUri,
                    modifiedEntity: modifiedEntity,
                    metadata: metadata,
                    existingValues: ((_b = currentExistingValue === null || currentExistingValue === void 0 ? void 0 : currentExistingValue.value) === null || _b === void 0 ? void 0 : _b[subAttrubuteType.name]) || [],
                    hasValues: hasExistingValues
                });
            }
        }
        return null;
    }
    return currentLevelUri;
};
var generateAttributeValueUri = function (_a) {
    var attributeTypeUri = _a.attributeTypeUri, modifiedEntity = _a.modifiedEntity, triggerAttributeTypeUri = _a.triggerAttributeTypeUri, triggerAttributeValueUri = _a.triggerAttributeValueUri, metadata = _a.metadata;
    var triggerAttributeNestedLevel = triggerAttributeTypeUri.split('/attributes/').length - 1;
    var attributeTypeRootUri = attributeTypeUri
        .split('/attributes/')
        .slice(0, Math.max(triggerAttributeNestedLevel, MINIMUM_NESTED_LEVEL) + 1)
        .join('/attributes/');
    var triggerAttributeValueParentUri = getParentUri(triggerAttributeValueUri);
    var rootAttributeType = findAttributeTypeByUri(metadata, attributeTypeRootUri, modifiedEntity.type);
    var existingValues = findAttributeValuesByTypeUri(metadata, modifiedEntity, rootAttributeType.uri).filter(isOv);
    return genAttributeValueUri({
        attributeType: rootAttributeType,
        parentValueUri: triggerAttributeValueParentUri,
        attributeTypeUri: attributeTypeUri,
        modifiedEntity: modifiedEntity,
        existingValues: existingValues,
        metadata: metadata
    });
};
var getCountriesFromValues = function (_a) {
    var _b;
    var metadata = _a.metadata, modifiedEntity = _a.modifiedEntity, triggerAttributeValueUri = _a.triggerAttributeValueUri, triggerAttributeTypeUri = _a.triggerAttributeTypeUri, inputMapping = _a.inputMapping;
    if (!triggerAttributeValueUri || !triggerAttributeTypeUri || !inputMapping || !modifiedEntity) {
        return {};
    }
    var triggerAttributeValueParentUri = getParentUri(triggerAttributeValueUri);
    var triggerAttributeTypeParentUri = getParentUri(triggerAttributeTypeUri);
    var countriesMapping = (_b = inputMapping
        .filter(function (_a) {
        var cleanseAttribute = _a.cleanseAttribute;
        return cleanseAttribute === InputCleanseAttributeType.Countries;
    })
        .filter(function (_a) {
        var attribute = _a.attribute;
        var attributeParentUri = getParentUri(attribute);
        return areOneHierarchyUris(triggerAttributeTypeParentUri, attributeParentUri);
    })
        .sort(function (a, b) { return b.attribute.length - a.attribute.length; })) === null || _b === void 0 ? void 0 : _b[0];
    var countryAttributeType = (countriesMapping === null || countriesMapping === void 0 ? void 0 : countriesMapping.attribute) &&
        findAttributeTypeByUri(metadata, countriesMapping === null || countriesMapping === void 0 ? void 0 : countriesMapping.attribute, modifiedEntity.type);
    if (countryAttributeType && !isComplexAttribute(countryAttributeType)) {
        var existingCountriesValues = findAttributeValuesByTypeUri(metadata, modifiedEntity, countriesMapping.attribute);
        var currentCountryValues = uniqBy(prop('value'), existingCountriesValues
            .filter(isOv)
            .filter(function (countryValue) {
            return areOneHierarchyUris(triggerAttributeValueParentUri, getParentUri(countryValue.uri));
        })
            .filter(function (countryValue) { return countryValue.value; }));
        if (currentCountryValues === null || currentCountryValues === void 0 ? void 0 : currentCountryValues.length) {
            var countries = currentCountryValues.map(function (value) { return value.lookupCode || value.value.toString(); });
            return {
                countries: countries,
                countryNames: pluck('value', currentCountryValues)
            };
        }
    }
};
export var getSettings = function (_a) {
    var _b, _c;
    var metadata = _a.metadata, modifiedEntity = _a.modifiedEntity, triggerAttributeValueUri = _a.triggerAttributeValueUri, triggerAttributeTypeUri = _a.triggerAttributeTypeUri, addressAutoCompleteConfig = _a.addressAutoCompleteConfig;
    var _d = addressAutoCompleteConfig.inputMapping, inputMapping = _d === void 0 ? [] : _d, minSearchTextLen = addressAutoCompleteConfig.minSearchTextLen, providerOpts = addressAutoCompleteConfig.providerOpts;
    return __assign({ minSearchTextLen: minSearchTextLen || MIN_SEARCH_TEXT_LEN, limit: (providerOpts === null || providerOpts === void 0 ? void 0 : providerOpts.limit) || SEARCH_RESULTS_LIMIT, countries: ((_b = providerOpts === null || providerOpts === void 0 ? void 0 : providerOpts.defaultCountries) === null || _b === void 0 ? void 0 : _b.split(COUNTRIES_DELIMETER)) || [], countryNames: ((_c = providerOpts === null || providerOpts === void 0 ? void 0 : providerOpts.defaultCountries) === null || _c === void 0 ? void 0 : _c.split(COUNTRIES_DELIMETER)) || [] }, getCountriesFromValues({
        metadata: metadata,
        modifiedEntity: modifiedEntity,
        triggerAttributeValueUri: triggerAttributeValueUri,
        triggerAttributeTypeUri: triggerAttributeTypeUri,
        inputMapping: inputMapping
    }));
};
export var isTriggerAttribute = function (attributeType, inputMapping) {
    var allowedTypes = [DataTypes.TYPE_STRING, DataTypes.TYPE_TEXT, DataTypes.TYPE_BLOB];
    return (allowedTypes.includes(attributeType.type) &&
        inputMapping.some(function (_a) {
            var attribute = _a.attribute, cleanseAttribute = _a.cleanseAttribute;
            return attributeType.uri === attribute && cleanseAttribute === InputCleanseAttributeType.Text;
        }));
};
export var modifyAttributes = function (_a) {
    var outputMapping = _a.outputMapping, modifiedEntity = _a.modifiedEntity, metadata = _a.metadata, triggerAttributeTypeUri = _a.triggerAttributeTypeUri, triggerAttributeValueUri = _a.triggerAttributeValueUri, values = _a.values, modifyAttribute = _a.modifyAttribute;
    var parentUri = getParentUri(triggerAttributeTypeUri);
    outputMapping
        .filter(function (_a) {
        var attribute = _a.attribute;
        return areOneHierarchyUris(attribute, parentUri);
    })
        .forEach(function (_a) {
        var attributeTypeUri = _a.attribute, cleanseAttribute = _a.cleanseAttribute;
        var value = values[cleanseAttribute] || '';
        var attributeType = findAttributeTypeByUri(metadata, attributeTypeUri, modifiedEntity.type);
        if (!attributeType) {
            return;
        }
        var uri = generateAttributeValueUri({
            attributeTypeUri: attributeTypeUri,
            triggerAttributeTypeUri: triggerAttributeTypeUri,
            triggerAttributeValueUri: triggerAttributeValueUri,
            modifiedEntity: modifiedEntity,
            metadata: metadata
        });
        if (uri) {
            modifyAttribute({
                value: value,
                uri: uri,
                attributeType: attributeType
            });
        }
    });
};
