"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __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 });
const React = __importStar(require("react"));
const PropTypes = __importStar(require("prop-types"));
const utils_1 = require("../../utils");
const components_1 = require("../components");
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const TagArrayField_1 = require("./TagArrayField");
/**
 * Compatible only with unit array.
 */
class UnitListShorthandArrayField extends React.Component {
    constructor() {
        super(...arguments);
        this.state = { show: false };
        this.onButtonClick = () => () => {
            this.setState({ show: !this.state.show });
        };
        this.onHide = () => {
            this.setState({ show: false, value: "" });
        };
        this.onTagFieldChange = (tags) => {
            this.setState({ value: tags.join(",") });
        };
        this.onSubmit = () => {
            const value = this.state.value + ((0, utils_1.isEmptyString)(this.tagRef.state.value) ? "" : `,${this.tagRef.state.value}`);
            this.onHide();
            const { translations, notifier, apiClient } = this.props.formContext;
            this.props.formContext.services.blocker.push();
            apiClient.get("/shorthand/unit/list", { query: { query: value } }).then(({ results, nonMatchingCount }) => {
                const units = results.map(unit => {
                    unit = (0, utils_1.getDefaultFormState)(this.props.schema.items, unit);
                    unit = (0, utils_1.bringRemoteFormData)(unit, this.props.formContext);
                    unit = (0, utils_1.assignUUID)(unit);
                    return unit;
                });
                const formData = this.props.formData;
                const last = formData[formData.length - 1];
                if (last && (0, utils_1.isDefaultData)(last, this.props.schema.items)) {
                    formData.pop();
                }
                this.props.onChange([...formData, ...units]);
                nonMatchingCount
                    ? notifier.warning(`${translations.UnitListShorthandWarning} ${nonMatchingCount}`)
                    : notifier.success(translations.UnitListShorthandSuccess);
                this.props.formContext.services.blocker.pop();
            });
        };
        this.onKeyDown = (e) => {
            if (e.key === "Enter") {
                this.onSubmit(e);
            }
        };
        this.setTagArrayRef = (ref) => {
            this.tagRef = ref;
        };
    }
    getUiSchema(props) {
        const buttonDefinition = {
            fn: this.onButtonClick,
            fnName: "addUnitList",
            glyph: "align-justify",
            label: props.formContext.translations.AddUnitList,
            id: props.idSchema.$id,
            changesFormData: true,
            rules: {
                canAdd: true
            }
        };
        const innerUiSchema = (0, utils_1.getInnerUiSchema)(props.uiSchema);
        const options = (0, utils_1.getUiOptions)(innerUiSchema);
        return Object.assign(Object.assign({}, innerUiSchema), { "ui:options": Object.assign(Object.assign({}, options), { buttons: [
                    ...(options.buttons || []),
                    buttonDefinition
                ] }) });
    }
    render() {
        const { SchemaField } = this.props.registry.fields;
        const { Modal } = this.context.theme;
        return (React.createElement(React.Fragment, null,
            React.createElement(SchemaField, Object.assign({}, this.props, { uiSchema: this.getUiSchema(this.props) })),
            this.state.show && (React.createElement(Modal, { show: true, onHide: this.onHide, dialogClassName: "unit-list-shorthand-modal" },
                React.createElement(Modal.Body, null,
                    React.createElement(TagArrayField_1.TagInputComponent, { tags: (0, utils_1.isEmptyString)(this.state.value) ? [] : this.state.value.split(",").filter(s => !(0, utils_1.isEmptyString)(s)), onChange: this.onTagFieldChange, schema: {}, idSchema: {}, uiSchema: { "ui:options": { separatorKeys: [","] } }, inputProps: { autoFocus: true }, onKeyDown: this.onKeyDown, ref: this.setTagArrayRef, formContext: this.props.formContext }),
                    React.createElement("span", { className: "text-muted" },
                        React.createElement("i", null, this.props.formContext.translations.UnitListShorthandHelp)),
                    React.createElement("br", null),
                    React.createElement(components_1.Button, { type: "submit", disabled: (0, utils_1.isEmptyString)(this.state.value), onClick: this.onSubmit }, this.props.formContext.translations.Add))))));
    }
}
UnitListShorthandArrayField.contextType = ReactContext_1.default;
UnitListShorthandArrayField.propTypes = {
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array"])
    }).isRequired,
    formData: PropTypes.array.isRequired
};
exports.default = UnitListShorthandArrayField;
