"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 SelectWidget_1 = __importDefault(require("../widgets/SelectWidget"));
const utils_1 = require("../../utils");
const components_1 = require("../components");
const memoizee_1 = __importDefault(require("memoizee"));
const immutability_helper_1 = __importDefault(require("immutability-helper"));
class PrefixArrayField extends React.Component {
    static getName() { return "PrefixArrayField"; }
    constructor(props) {
        super(props);
        this.onSelectFieldChange = (prefix) => {
            const separator = this.getSeparator(this.props.uiSchema);
            const newFormData = [...(this.props.formData || []), prefix + separator];
            this.props.onChange(newFormData);
        };
        this.onFieldChange = (0, memoizee_1.default)((idx) => (value) => {
            const separator = this.getSeparator(this.props.uiSchema);
            const newValue = this.state.fieldValues[idx].prefix + separator + value;
            const newFormData = (0, immutability_helper_1.default)(this.props.formData, { [idx]: { $set: newValue } });
            this.props.onChange(newFormData);
        });
        this.onFieldDelete = (0, memoizee_1.default)((idx) => () => {
            const newFormData = (0, immutability_helper_1.default)(this.props.formData, { $splice: [[idx, 1]] });
            this.props.onChange(newFormData);
        });
        this.state = this.getStateFromProps(props);
    }
    UNSAFE_componentWillReceiveProps(props) {
        this.setState(this.getStateFromProps(props));
    }
    getSeparator(uiSchema) {
        const { separator = ":" } = (0, utils_1.getUiOptions)(uiSchema);
        return separator;
    }
    getStateFromProps(props) {
        const { formData = [], uiSchema } = props;
        const separator = this.getSeparator(uiSchema);
        return {
            fieldValues: formData.map((value) => {
                const sepIdx = value.indexOf(separator);
                return {
                    prefix: value.substring(0, sepIdx),
                    value: value.substring(sepIdx + 1)
                };
            })
        };
    }
    render() {
        const SchemaField = this.props.registry.fields.SchemaField;
        const { schema, uiSchema, idSchema, errorSchema, required, disabled, readonly, formContext: { Label, translations, uiSchemaContext } } = this.props;
        const { prefixValues = [], addFieldPlaceholder, confirmDelete = uiSchemaContext.confirmDelete } = (0, utils_1.getUiOptions)(uiSchema);
        const childProps = this.state.fieldValues.map((value, idx) => {
            return {
                schema: schema.items,
                uiSchema: {
                    "ui:title": "",
                    "ui:widget": "InputGroupWidget",
                    "ui:options": Object.assign({ "inputGroupText": value.prefix, "className": "condensed-object-field-input-group" }, (uiSchema["ui:options"] || {})),
                },
                idSchema: { $id: `${idSchema.$id}_${idx}` },
                errorSchema: errorSchema[idx] || {},
                formData: value.value
            };
        });
        const selectableFieldEnums = prefixValues.map((value) => ({
            value,
            label: value
        }));
        return (React.createElement(React.Fragment, null,
            React.createElement(Label, { label: this.props.schema.title, required: required || uiSchema["ui:required"], id: this.props.idSchema.$id, uiSchema: this.props.uiSchema }),
            childProps.map((props, idx) => React.createElement("div", { key: idx, className: "laji-form-field-template-item condensed-object-field-item" },
                React.createElement("div", { className: "laji-form-field-template-schema" },
                    React.createElement(SchemaField, Object.assign({}, this.props, props, { key: idx, onChange: this.onFieldChange(idx) }))),
                React.createElement("div", { className: "laji-form-field-template-buttons" },
                    React.createElement(components_1.DeleteButton, { id: props.idSchema.$id, onClick: this.onFieldDelete(idx), translations: translations, confirm: confirmDelete, disabled: disabled || readonly })))),
            React.createElement(SelectWidget_1.default, { key: childProps.length, options: { enumOptions: selectableFieldEnums, placeholder: addFieldPlaceholder !== null && addFieldPlaceholder !== void 0 ? addFieldPlaceholder : `${translations.AddField}` }, onChange: this.onSelectFieldChange, includeEmpty: true, schema: {}, id: `${idSchema.$id}_field_select`, formContext: this.props.formContext, disabled: this.props.disabled, readonly: this.props.readonly })));
    }
}
PrefixArrayField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            prefixValues: PropTypes.arrayOf(PropTypes.string).isRequired,
            separator: PropTypes.string,
            addFieldPlaceholder: PropTypes.string
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array"])
    }).isRequired,
    formData: PropTypes.array
};
exports.default = PrefixArrayField;
