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));
};
import React from 'react';
import i18n from 'ui-i18n';
import { both, either, filter, pick, pipe, propEq, propOr, reject } from 'ramda';
import { checkCanCreateAttribute, isImage, isNested, isReadableAttribute, isReference, Mode } from '@reltio/mdm-sdk';
import { MoreAttributesButton } from '../../../../../MoreAttributesButton';
import { withTableContext } from '../../../../../HOCs/withTableContext';
import { useMdmMetadata } from '../../../../../contexts/MdmModuleContext';
import { useStyles } from './styles';
var AddAttributesButton = function (_a) {
    var parentTypeUri = _a.parentTypeUri, parentUri = _a.parentUri, selectedAttributeTypes = _a.selectedAttributeTypes, onSelectAttributeTypes = _a.onSelectAttributeTypes, onAdd = _a.onAdd;
    var styles = useStyles();
    var metadata = useMdmMetadata();
    var parentType = __spreadArray(__spreadArray([], metadata.entityTypes, true), (metadata.relationTypes || []), true).find(propEq('uri', parentTypeUri));
    var isNotSelected = function (attrType) { return !(selectedAttributeTypes === null || selectedAttributeTypes === void 0 ? void 0 : selectedAttributeTypes.find(propEq('uri', attrType.uri))); };
    var canCreate = function (attributeType) { return checkCanCreateAttribute({ attributeType: attributeType, mode: Mode.Editing }); };
    var data = pipe(propOr([], 'attributes'), reject(either(isReference, isImage)), filter(either(isNested, isNotSelected)), filter(both(isReadableAttribute, canCreate)))(parentType);
    var handleAdd = function (addedTypes) {
        var typesToSelect = addedTypes.filter(isNotSelected);
        if (typesToSelect.length > 0) {
            onSelectAttributeTypes(__spreadArray(__spreadArray([], typesToSelect, true), selectedAttributeTypes, true));
        }
        addedTypes.filter(isNested).forEach(function (attributeType) {
            onAdd({ attributeType: attributeType, parentUri: parentUri });
        });
    };
    return (React.createElement("div", { className: styles.root },
        React.createElement(MoreAttributesButton, { label: i18n.text('Attribute'), popupTitle: i18n.text('Add attributes'), data: data, onApply: handleAdd })));
};
export default withTableContext(pick(['parentUri', 'parentTypeUri', 'onAdd', 'selectedAttributeTypes', 'onSelectAttributeTypes']))(AddAttributesButton);
