"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 __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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
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 ramda_1 = require("ramda");
var react_context_selector_1 = require("@fluentui/react-context-selector");
var Add_1 = __importDefault(require("@mui/icons-material/Add"));
var Delete_1 = __importDefault(require("@mui/icons-material/Delete"));
var Typography_1 = __importDefault(require("@mui/material/Typography"));
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var DataTypeValue_1 = require("../DataTypeValue");
var DataTypeValueEditor_1 = require("../DataTypeValueEditor");
var ErrorWrapper_1 = require("../ErrorWrapper");
var SmallIconButton_1 = require("../SmallIconButton");
var helpers_1 = require("./helpers");
var attributesView_1 = require("../helpers/attributesView");
var withAsyncMount_1 = require("../HOCs/withAsyncMount");
var withContext_1 = require("../HOCs/withContext");
var ProfilePerspectiveViewContext_1 = require("../contexts/ProfilePerspectiveViewContext");
var ScrollToElementContext_1 = require("../contexts/ScrollToElementContext");
var MdmModuleContext_1 = require("../contexts/MdmModuleContext");
var useScrollToAttributeError_1 = require("../hooks/useScrollToAttributeError");
var useAutopopulationContextValue_1 = require("./useAutopopulationContextValue");
var useAttributeValuePermissions_1 = require("./useAttributeValuePermissions");
var DependentLookupAutopopulationContext_1 = require("../contexts/DependentLookupAutopopulationContext");
var styles_1 = require("./styles");
var AutoCompleteContext_1 = require("../contexts/AutoCompleteContext");
var AttributeValueContext_1 = require("../contexts/AttributeValueContext");
var AuthoringPerspectiveViewContext_1 = require("../contexts/AuthoringPerspectiveViewContext");
var AsyncMountPlaceholder = function () {
    var styles = (0, styles_1.useStyles)();
    return react_1.default.createElement("div", { className: styles.placeholder });
};
var SimpleAttributeEditor = function (_a) {
    var _b, _c;
    var _d;
    var className = _a.className, attributeValue = _a.attributeValue, attributeType = _a.attributeType, isReltioCrosswalk = _a.isReltioCrosswalk, ownError = _a.ownError, mode = _a.mode, onAddOneMore = _a.onAddOneMore, onDeleteAttribute = _a.onDeleteAttribute, onChangeAttribute = _a.onChangeAttribute, onDeactivateError = _a.onDeactivateError, additionalControlsRenderer = _a.additionalControlsRenderer, state = _a.state, highlightedError = _a.highlightedError, _e = _a.isEmptyEditor, isEmptyEditor = _e === void 0 ? false : _e, isFirstEditor = _a.isFirstEditor, otherProps = __rest(_a, ["className", "attributeValue", "attributeType", "isReltioCrosswalk", "ownError", "mode", "onAddOneMore", "onDeleteAttribute", "onChangeAttribute", "onDeactivateError", "additionalControlsRenderer", "state", "highlightedError", "isEmptyEditor", "isFirstEditor"]);
    var styles = (0, styles_1.useStyles)();
    var deleted = state === 'deleted';
    var edited = state === 'edited';
    var isEditableMode = (0, mdm_sdk_1.isEditableMode)(mode);
    var _f = (0, useAttributeValuePermissions_1.useAttributeValuePermissions)({
        attributeValue: attributeValue,
        attributeType: attributeType,
        mode: mode,
        isReltioCrosswalk: isReltioCrosswalk
    }), canCreate = _f.canCreate, canEdit = _f.canEdit, canDelete = _f.canDelete;
    var showToEdit = canEdit && isEditableMode && !attributeValue.masked;
    var errorMessage = (0, mdm_sdk_1.getErrorMessage)(ownError);
    var dependentLookupEditorContext = (0, MdmModuleContext_1.useMdmDependentLookupEditorContext)(attributeValue, attributeType);
    var isAutocompleteTriggerAttribute = (0, react_context_selector_1.useContextSelector)(AutoCompleteContext_1.AddressAutoCompleteContext, function (c) { return c === null || c === void 0 ? void 0 : c.isAutocompleteTriggerAttribute; });
    var _g = (0, useScrollToAttributeError_1.useScrollToAttributeError)({ highlightedError: highlightedError, isSimple: true }), ref = _g.ref, errorClassName = _g.errorClassName;
    (0, react_1.useEffect)(function () {
        // when editor is empty but has default lookup code, onChangeAttribute will be called by useLookupsResolver
        if (isEmptyEditor && (0, mdm_sdk_1.isDependentLookupAttrType)(attributeType) && !(0, ramda_1.has)('lookupCode', attributeValue)) {
            onChangeAttribute({
                attributeType: attributeType,
                uri: attributeValue.uri,
                value: attributeValue.value,
                silent: true
            });
        }
    }, [isEmptyEditor]);
    var dataTypeDefinition = (0, react_1.useMemo)(function () {
        var dataTypeDefinition = (0, mdm_sdk_1.getAttrDataTypeDefinition)(attributeType);
        if (isFirstEditor && (isAutocompleteTriggerAttribute === null || isAutocompleteTriggerAttribute === void 0 ? void 0 : isAutocompleteTriggerAttribute(attributeType))) {
            return __assign(__assign({}, dataTypeDefinition), { type: mdm_sdk_1.DataTypes.TYPE_ADDRESS_AUTOCOMPLETE });
        }
        return dataTypeDefinition;
    }, [attributeType, isAutocompleteTriggerAttribute, isFirstEditor]);
    var value = (0, react_1.useMemo)(function () { return (0, attributesView_1.attributeValueToEditorValue)(attributeValue, dataTypeDefinition); }, [attributeValue, dataTypeDefinition]);
    var deactivateError = (0, react_1.useCallback)(function () {
        if (ownError) {
            onDeactivateError((0, mdm_sdk_1.getErrorId)(ownError));
        }
    }, [ownError, onDeactivateError]);
    var onValueEditorChange = (0, react_1.useCallback)((0, ramda_1.pipe)((0, helpers_1.prepareChangeData)(attributeValue, attributeType), onChangeAttribute, deactivateError), [attributeValue, attributeType, onChangeAttribute, deactivateError]);
    var onDelete = function () {
        onDeleteAttribute({ uri: attributeValue.uri, attributeType: attributeType });
        if ((0, mdm_sdk_1.getErrorType)(ownError) !== mdm_sdk_1.ErrorType.missed) {
            deactivateError();
        }
    };
    var maxCardinalityIsOne = ((_d = attributeType === null || attributeType === void 0 ? void 0 : attributeType.cardinality) === null || _d === void 0 ? void 0 : _d.maxValue) === 1;
    var showAddButton = !!onAddOneMore &&
        canCreate &&
        !attributeType.singleValue &&
        !attributeValue.masked &&
        mode !== mdm_sdk_1.Mode.Viewing &&
        !maxCardinalityIsOne;
    var showDeleteButton = !deleted && !!onDeleteAttribute && canDelete && !attributeValue.masked && mode !== mdm_sdk_1.Mode.Viewing;
    var hasError = !!errorMessage;
    var deletedProps = deleted ? { disabled: true, isCrossedOut: true } : {};
    var isProfilePerspectiveView = (0, react_1.useContext)(ProfilePerspectiveViewContext_1.ProfilePerspectiveViewContext);
    var isAuthoringPerspectiveView = (0, react_1.useContext)(AuthoringPerspectiveViewContext_1.AuthoringPerspectiveViewContext);
    var isEntityPerspectiveView = isProfilePerspectiveView || isAuthoringPerspectiveView;
    var autopopulationContextValue = (0, useAutopopulationContextValue_1.useAutopopulationContextValue)({
        enabled: isEntityPerspectiveView && (0, mdm_sdk_1.isDependentLookupAttrType)(attributeType),
        attributeTypeUri: attributeType === null || attributeType === void 0 ? void 0 : attributeType.uri,
        valueUri: attributeValue.uri
    }).autopopulationContextValue;
    return (react_1.default.createElement("div", { ref: ref, "data-reltio-id": "simple-attribute-editor", className: (0, classnames_1.default)(styles.editor, className, errorClassName) },
        react_1.default.createElement(ErrorWrapper_1.ErrorWrapper, { errorMessage: errorMessage, className: styles.errorWrapper },
            react_1.default.createElement("div", { className: (0, classnames_1.default)(styles['editor-value'], (_b = {}, _b[styles.deleted] = deleted, _b), (_c = {}, _c[styles['editor-read-only-value']] = !showToEdit, _c)), "data-reltio-id": "reltio-attribute-value" }, showToEdit ? (react_1.default.createElement(DependentLookupAutopopulationContext_1.DependentLookupAutopopulationContext.Provider, { value: autopopulationContextValue },
                react_1.default.createElement(AttributeValueContext_1.AttributeValueContext.Provider, { value: attributeValue },
                    react_1.default.createElement(DataTypeValueEditor_1.DataTypeValueEditor, __assign({ fieldName: (0, mdm_sdk_1.attributeUriToSearchUri)(attributeType.uri), value: value, dataTypeDefinition: dataTypeDefinition, error: hasError, onChange: onValueEditorChange, fullWidth: true }, dependentLookupEditorContext, otherProps, deletedProps))))) : (react_1.default.createElement(DataTypeValue_1.DataTypeValue, { value: (0, mdm_sdk_1.getAttributeValue)(attributeValue), dataTypeDefinition: dataTypeDefinition })))),
        react_1.default.createElement("div", { "data-reltio-id": "reltio-attribute-actions", className: styles['editor-actions'] },
            edited && (react_1.default.createElement(Typography_1.default, { variant: "caption", className: styles.editedLabel },
                "(",
                ui_i18n_1.default.text('edited'),
                ")")),
            showAddButton && (react_1.default.createElement(SmallIconButton_1.SmallIconButton, { icon: Add_1.default, onClick: onAddOneMore, size: "L", className: (0, classnames_1.default)(styles.addButton, styles.button), "data-reltio-id": "reltio-add-one-more-simple-attribute-button" })),
            additionalControlsRenderer && additionalControlsRenderer({ attributeType: attributeType, attributeValue: attributeValue }),
            showDeleteButton && (react_1.default.createElement(SmallIconButton_1.SmallIconButton, { className: styles.button, icon: Delete_1.default, onClick: onDelete, size: "L", "data-reltio-id": "reltio-delete-simple-attribute-button" })))));
};
var SimpleAttributeEditorWithScrollToElementContext = (0, withContext_1.withContext)(ScrollToElementContext_1.ScrollToElementContext, function (contextValue, _a) {
    var attributeValue = _a.attributeValue;
    var _b = contextValue || {}, element = _b.element, type = _b.type;
    var isHighlighted = (0, ScrollToElementContext_1.isHighlightedErrorType)(type) && (element === null || element === void 0 ? void 0 : element.uri) === attributeValue.uri;
    return { highlightedError: isHighlighted ? contextValue : null };
}, SimpleAttributeEditor);
exports.default = (0, withAsyncMount_1.withAsyncMount)(SimpleAttributeEditorWithScrollToElementContext, AsyncMountPlaceholder);
