"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importStar(require("react"));
var classnames_1 = __importDefault(require("classnames"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var ramda_1 = require("ramda");
var BranchDecorator_1 = require("../../../BranchDecorator");
var ErrorMessage_1 = require("../../../ErrorMessage");
var AttributeTitle_1 = require("../../../AttributeTitle");
var OvIcon_1 = require("../../../OvIcon");
var ShowLess_1 = require("../../../ShowLess");
var ShowMore_1 = require("../../../ShowMore");
var EditModeAttributesFactory_1 = require("../../../EditModeAttributesFactory");
var CardinalityMessage_1 = require("../../../CardinalityMessage");
var PinnedAttributesContext_1 = require("../../../contexts/PinnedAttributesContext");
var AlwaysVisibleAttributesContext_1 = require("../../../contexts/AlwaysVisibleAttributesContext");
var DescriptionIcon_1 = require("../../../DescriptionIcon");
var ControlAttributeIcon_1 = require("../../../ControlAttributeIcon");
var useScrollToAttribute_1 = require("../../../hooks/useScrollToAttribute");
var useScrollToAttributeError_1 = require("../../../hooks/useScrollToAttributeError");
var MdmModuleContext_1 = require("../../../contexts/MdmModuleContext");
var helpers_1 = require("../../helpers");
var styles_1 = require("../../styles");
var AttributeRenderer = function (_a) {
    var max = _a.max, values = _a.values, attributeType = _a.attributeType, parentUri = _a.parentUri, mode = _a.mode, drawLines = _a.drawLines, showEmptyEditors = _a.showEmptyEditors, errorMessage = _a.errorMessage, errors = _a.errors, paging = _a.paging, crosswalks = _a.crosswalks, showNonOv = _a.showNonOv, nonVisibleValues = _a.nonVisibleValues, highlightedError = _a.highlightedError, highlightedAttribute = _a.highlightedAttribute, onAddAttributes = _a.onAddAttributes, onDeleteAttribute = _a.onDeleteAttribute, onChangeAttribute = _a.onChangeAttribute, onDeactivateError = _a.onDeactivateError, additionalControlsRenderer = _a.additionalControlsRenderer, requestNextPageOfAttributeValues = _a.requestNextPageOfAttributeValues;
    var styles = (0, styles_1.useStyles)();
    var _b = (0, react_1.useState)(max), visibleValuesCount = _b[0], setVisibleValuesCount = _b[1];
    var _c = (0, react_1.useState)(false), hadDeletions = _c[0], setHadDeletions = _c[1];
    var label = attributeType.label, isRequired = attributeType.required, cardinality = attributeType.cardinality, name = attributeType.name, attributeTypeUri = attributeType.uri, description = attributeType.description;
    var isEditableMode = (0, mdm_sdk_1.isEditableMode)(mode);
    var _d = (0, useScrollToAttributeError_1.useScrollToAttributeError)({ highlightedError: highlightedError }), errorRef = _d.ref, errorClassName = _d.errorClassName;
    var _e = (0, useScrollToAttribute_1.useScrollToAttribute)(highlightedAttribute), attributeRef = _e.ref, highlightedClassName = _e.highlightedClassName;
    var pinnedAttributes = (0, react_1.useContext)(PinnedAttributesContext_1.PinnedAttributesContext);
    var alwaysVisibleAttributes = (0, react_1.useContext)(AlwaysVisibleAttributesContext_1.AlwaysVisibleAttributesContext);
    var isPinned = (0, react_1.useMemo)(function () { return pinnedAttributes === null || pinnedAttributes === void 0 ? void 0 : pinnedAttributes.includes(attributeTypeUri); }, [attributeTypeUri, pinnedAttributes]);
    var isAlwaysVisible = (0, react_1.useMemo)(function () { return alwaysVisibleAttributes === null || alwaysVisibleAttributes === void 0 ? void 0 : alwaysVisibleAttributes.includes(attributeTypeUri); }, [attributeTypeUri, alwaysVisibleAttributes]);
    var isEmptyValues = (0, mdm_sdk_1.isEmptyValue)(values);
    var showEmpty = ((!hadDeletions && showEmptyEditors) || isRequired || isPinned || isAlwaysVisible) && isEmptyValues;
    var controlAttributes = (0, MdmModuleContext_1.useMdmControlAttributes)();
    var isControlAttribute = (0, react_1.useMemo)(function () { return controlAttributes.includes(attributeType.uri); }, [controlAttributes, attributeType.uri]);
    var emptyEditorValue = (0, react_1.useRef)((0, mdm_sdk_1.createNewAttribute)({
        parentUri: parentUri,
        attributeType: (0, ramda_1.omit)(['defaultValue'], attributeType)
    }));
    var onAddOneMore = (0, react_1.useCallback)(function () {
        setVisibleValuesCount(visibleValuesCount + 1);
        var createAttribute = function (attributeType) { return ({
            parentUri: parentUri,
            index: visibleValuesCount,
            attributeType: attributeType
        }); };
        if (showEmpty && !(0, mdm_sdk_1.isComplexAttribute)(attributeType.type)) {
            var attributes = [createAttribute((0, ramda_1.omit)(['defaultValue'], attributeType)), createAttribute(attributeType)];
            return onAddAttributes(attributes);
        }
        return onAddAttributes([createAttribute(attributeType)]);
    }, [visibleValuesCount, onAddAttributes, parentUri, attributeType, showEmpty]);
    var onDelete = (0, react_1.useCallback)((0, ramda_1.pipe)(onDeleteAttribute, ramda_1.T, setHadDeletions), [onDeleteAttribute, setHadDeletions]);
    if (isEmptyValues && !showEmpty) {
        return null;
    }
    if (showEmpty && isEmptyValues) {
        values = [emptyEditorValue.current];
    }
    if ((0, mdm_sdk_1.isEmptyValue)(values)) {
        return null;
    }
    var newValuesCount = ((0, helpers_1.filterNewValues)(values) || []).length;
    var totalProp = showNonOv ? 'totalValues' : 'totalOvValues';
    var totalVisibleValues = (0, ramda_1.ifElse)((0, ramda_1.has)(totalProp), (0, ramda_1.pipe)((0, ramda_1.prop)(totalProp), (0, ramda_1.add)(newValuesCount)), (0, ramda_1.always)(values.length))(paging);
    var totalNonVisibleValues = (paging === null || paging === void 0 ? void 0 : paging.totalValues)
        ? paging.totalValues - totalVisibleValues
        : nonVisibleValues === null || nonVisibleValues === void 0 ? void 0 : nonVisibleValues.length;
    var hasPaging = max < totalVisibleValues;
    var showMore = hasPaging && visibleValuesCount < totalVisibleValues;
    var showLess = hasPaging && visibleValuesCount >= totalVisibleValues;
    var onShowMore = function () {
        if (values.length < totalVisibleValues) {
            requestNextPageOfAttributeValues({
                parentUri: parentUri,
                attributeTypeUri: attributeTypeUri,
                attributeTypeName: name,
                values: values,
                defaultMaxValues: max
            });
        }
        setVisibleValuesCount(visibleValuesCount + max);
    };
    var onShowLess = function () {
        setVisibleValuesCount(max);
    };
    var shownValues = values.slice(0, visibleValuesCount);
    var lastIndex = shownValues ? shownValues.length - 1 : 0;
    var hiddenValuesCount = totalVisibleValues - visibleValuesCount;
    return (react_1.default.createElement(BranchDecorator_1.BranchDecorator, { enabled: drawLines },
        react_1.default.createElement("div", { ref: errorRef, className: (0, classnames_1.default)(styles.wrapper, errorClassName) },
            react_1.default.createElement("div", { className: styles.titleWrapper },
                react_1.default.createElement(AttributeTitle_1.AttributeTitle, { label: label, isRequired: isRequired, className: styles.title, "data-reltio-id": "reltio-attribute-label" }),
                react_1.default.createElement(DescriptionIcon_1.DescriptionIcon, { description: description }),
                isControlAttribute && react_1.default.createElement(ControlAttributeIcon_1.ControlAttributeIcon, null),
                react_1.default.createElement(OvIcon_1.OvIcon, { nonOvValues: nonVisibleValues, attributeType: attributeType, className: styles.ovIcon, nonOvTotal: totalNonVisibleValues })),
            isEditableMode && react_1.default.createElement(CardinalityMessage_1.CardinalityMessage, { cardinality: cardinality }),
            isEditableMode && react_1.default.createElement(ErrorMessage_1.ErrorMessage, { message: errorMessage, className: styles.typeError }),
            react_1.default.createElement("div", { className: styles.attributesWrapper },
                shownValues.map(function (value, idx) { return (react_1.default.createElement(EditModeAttributesFactory_1.EditModeAttribute, { key: value.uri, attributeValue: value, attributeType: attributeType, lazy: showEmpty && !isRequired, showEmptyEditors: showEmptyEditors, errors: errors, ownError: (0, mdm_sdk_1.getAttributeOwnError)(value, idx, attributeType.uri, errors), mode: mode, crosswalks: crosswalks, onAddOneMore: lastIndex === idx ? onAddOneMore : null, onAddAttributes: onAddAttributes, onDeleteAttribute: onDelete, onChangeAttribute: onChangeAttribute, onDeactivateError: onDeactivateError, additionalControlsRenderer: additionalControlsRenderer, className: idx === 0 ? highlightedClassName : null, ref: idx === 0 ? attributeRef : null, isFirstEditor: idx === 0, isEmptyEditor: showEmpty })); }),
                showMore && (react_1.default.createElement(ShowMore_1.ShowMore, { moreNumber: (0, ramda_1.min)(max, hiddenValuesCount), valueNumber: hiddenValuesCount, onClick: onShowMore })),
                showLess && react_1.default.createElement(ShowLess_1.ShowLess, { onClick: onShowLess })))));
};
AttributeRenderer.displayName = 'AttributeRenderer';
exports.default = (0, react_1.memo)(AttributeRenderer);
