"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 });
exports.EntitySelector = void 0;
var react_1 = __importStar(require("react"));
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var ramda_1 = require("ramda");
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var EmptyStub_1 = require("../EmptyStub");
var DropDownSelector_1 = require("../DropDownSelector");
var EntityOption_1 = require("./components/EntityOption");
var SingleValue_1 = require("./components/SingleValue");
var ClearIndicator_1 = require("./components/ClearIndicator");
var Group_1 = require("./components/Group");
var EntityCreator_1 = require("../EntityCreator");
var helpers_1 = require("./helpers");
var styles_1 = require("./styles");
var DEFAULT_MAX_TYPEAHEAD_SEARCH_OPTION = 20;
var EntitySelector = function (_a) {
    var _b = _a.entity, entity = _b === void 0 ? {} : _b, _c = _a.entityTypesUris, entityTypesUris = _c === void 0 ? [] : _c, mode = _a.mode, _d = _a.max, max = _d === void 0 ? DEFAULT_MAX_TYPEAHEAD_SEARCH_OPTION : _d, onChange = _a.onChange, onCreate = _a.onCreate, metadata = _a.metadata, globalSearchRequestOptions = _a.globalSearchRequestOptions, attributeTypesSelectionStrategy = _a.attributeTypesSelectionStrategy, _e = _a.disableLinkClick, disableLinkClick = _e === void 0 ? false : _e, _f = _a.isMasked, isMasked = _f === void 0 ? false : _f, otherProps = __rest(_a, ["entity", "entityTypesUris", "mode", "max", "onChange", "onCreate", "metadata", "globalSearchRequestOptions", "attributeTypesSelectionStrategy", "disableLinkClick", "isMasked"]);
    var styles = (0, styles_1.useStyles)();
    var _g = (0, react_1.useState)(''), inputValue = _g[0], setInputValue = _g[1];
    var entityTypes = (0, react_1.useMemo)(function () { return entityTypesUris.map(function (type) { return (0, mdm_sdk_1.getEntityType)(metadata, type); }).filter(mdm_sdk_1.isAvailableEntityType); }, [entityTypesUris, metadata]);
    var creatableEntityTypesUris = (0, react_1.useMemo)(function () {
        return entityTypesUris.filter(function (entityTypeUri) {
            var entityType = (0, mdm_sdk_1.getEntityType)(metadata, entityTypeUri);
            return (0, mdm_sdk_1.checkMetadataForCreate)(mode, entityType);
        });
    }, [entityTypesUris, mode, metadata]);
    var canCreateEntity = (0, react_1.useCallback)(function (entityTypeUri) {
        if (entityTypes.length === 0) {
            return false;
        }
        return creatableEntityTypesUris.includes(entityTypeUri !== null && entityTypeUri !== void 0 ? entityTypeUri : entityTypes[0].uri);
    }, [creatableEntityTypesUris, entityTypes]);
    var options = (0, react_1.useMemo)(function () { return (__assign(__assign({}, globalSearchRequestOptions), { max: max, sendMasked: isMasked })); }, [globalSearchRequestOptions, isMasked, max]);
    var handleCreate = onCreate
        ? function (value, entityTypeUri) {
            onCreate(entityTypeUri || entityTypes[0].uri, value);
            setInputValue('');
        }
        : undefined;
    var handleInputChange = function (value) {
        setInputValue(value);
    };
    var handleChange = function (value) {
        if (value !== null) {
            setInputValue('');
            onChange(value);
        }
    };
    var handleClear = function () {
        handleChange({});
    };
    var groupMode = (0, react_1.useMemo)(function () { return entityTypes.length !== 1; }, [entityTypes]);
    var getOptions = (0, react_1.useCallback)(function (value) {
        return ((0, ramda_1.isEmpty)(entityTypes) ? Promise.resolve([]) : (0, mdm_sdk_1.typeAheadSearch)(entityTypes, value, options)).then((0, helpers_1.buildEntityOptions)(entityTypes, onCreate));
    }, [entityTypes, onCreate, options]);
    var currentEntityType = ((0, ramda_1.isEmpty)(entity) ? entityTypes[0] : (0, mdm_sdk_1.getEntityType)(metadata, entity.entityType)) || {};
    var createLabel = onCreate &&
        (inputValue
            ? ui_i18n_1.default.text('Create "${name}" as new ${entityTypeLabel}', {
                name: inputValue,
                entityTypeLabel: currentEntityType.label
            })
            : ui_i18n_1.default.text('Create new ${entityTypeLabel}', { entityTypeLabel: currentEntityType.label }));
    var label = ui_i18n_1.default.text('Select ${entityTypeLabel}profile', {
        entityTypeLabel: entityTypes.length === 1 ? "".concat(entityTypes[0].label, " ") : ''
    });
    var isTempEntity = !(0, ramda_1.isEmpty)(entity) && (0, mdm_sdk_1.isTempUri)(entity.entityUri);
    var groupComponent = groupMode ? { Group: Group_1.Group, GroupHeading: EmptyStub_1.EmptyStub } : {};
    var clearComponent = isTempEntity ? { ClearIndicator: ClearIndicator_1.ClearIndicator } : {};
    var TextFieldProps = otherProps.TextFieldProps, dropDownSelectorProps = __rest(otherProps, ["TextFieldProps"]);
    var textFieldProps = (0, react_1.useMemo)(function () {
        var _a;
        return (__assign(__assign({}, (TextFieldProps || {})), (_a = {}, _a['data-reltio-id'] = 'reltio-entity-selector', _a)));
    }, [TextFieldProps]);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(DropDownSelector_1.DropDownSelector, __assign({ value: !(0, ramda_1.isEmpty)(entity) ? entity : undefined, inputValue: inputValue, onInputChange: handleInputChange, getOptions: getOptions, getOptionLabel: (0, ramda_1.prop)('entityLabel'), onChange: handleChange, onCreate: handleCreate, onClear: handleClear, label: label, createLabel: createLabel, canCreateOption: canCreateEntity, components: __assign(__assign({ Option: EntityOption_1.EntityOption, SingleValue: SingleValue_1.SingleValue }, groupComponent), clearComponent), currentEntityType: currentEntityType, isClearable: true, disableLinkClick: disableLinkClick, TextFieldProps: textFieldProps }, dropDownSelectorProps)),
        isTempEntity && (react_1.default.createElement("div", { "data-reltio-id": "entity-creator", className: styles.creatorWrapper },
            react_1.default.createElement(EntityCreator_1.EntityCreator, { mode: mode, attributeTypesSelectionStrategy: attributeTypesSelectionStrategy, entityType: currentEntityType, entityUri: entity.entityUri })))));
};
exports.EntitySelector = EntitySelector;
