"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 immutability_helper_1 = __importDefault(require("immutability-helper"));
const memoizee_1 = __importDefault(require("memoizee"));
const equals = require("deep-equal");
class CondensedObjectField extends React.Component {
    static getName() { return "CondensedObjectField"; }
    constructor(props) {
        super(props);
        this.onSelectFieldChange = (name) => {
            var _a;
            if (!name) {
                return;
            }
            const selectedFields = this.state.selectedFields;
            const type = this.props.schema.properties[name].type;
            let field;
            let fieldFormData;
            if (type !== "array") {
                field = { type, name, value: undefined };
                fieldFormData = undefined;
            }
            else {
                field = { type, name, idx: this.getArrayFieldNextIdx(selectedFields, name), value: undefined };
                fieldFormData = [...(((_a = this.props.formData) === null || _a === void 0 ? void 0 : _a[name]) || []), undefined];
            }
            const newSelectedFields = [...selectedFields, field];
            const newFormData = Object.assign(Object.assign({}, (this.props.formData || {})), { [name]: fieldFormData });
            this.setState({ selectedFields: newSelectedFields, formData: newFormData });
            this.props.onChange(newFormData);
        };
        this.onFieldChange = (0, memoizee_1.default)((idx) => (formData) => {
            const selectedFields = this.state.selectedFields;
            const field = selectedFields[idx];
            let newSelectedFields = (0, immutability_helper_1.default)(selectedFields, { [idx]: { ["value"]: { $set: formData } } });
            let newFormData;
            if (field.type !== "array") {
                newFormData = Object.assign(Object.assign({}, this.props.formData), { [field.name]: formData });
            }
            else {
                newFormData = (0, immutability_helper_1.default)(this.props.formData, { [field.name]: { [field.idx]: { $set: formData } } });
            }
            this.setState({ selectedFields: newSelectedFields, formData: newFormData });
            this.props.onChange(newFormData);
        });
        this.onFieldDelete = (0, memoizee_1.default)((idx) => () => {
            const selectedFields = this.state.selectedFields;
            const field = selectedFields[idx];
            let newSelectedFields = (0, immutability_helper_1.default)(selectedFields, { $splice: [[idx, 1]] });
            let newFormData;
            if (field.type !== "array" || this.props.formData[field.name].length === 1) {
                newFormData = (0, immutability_helper_1.default)(this.props.formData, { $unset: [field.name] });
            }
            else {
                newSelectedFields.forEach((f, idx) => {
                    if (f.type === "array" && f.name === field.name && f.idx > field.idx) {
                        newSelectedFields = (0, immutability_helper_1.default)(newSelectedFields, { [idx]: { ["idx"]: { $set: f.idx - 1 } } });
                    }
                });
                newFormData = (0, immutability_helper_1.default)(this.props.formData, { [field.name]: { $splice: [[field.idx, 1]] } });
            }
            if (Object.keys(newFormData).length === 0) {
                newFormData = undefined;
            }
            this.setState({ selectedFields: newSelectedFields, formData: newFormData });
            this.props.onChange(newFormData);
        });
        this.state = { selectedFields: this.getSelectedFieldsFromProps(props), formData: props.formData };
    }
    componentDidUpdate() {
        if (!equals(this.props.formData, this.state.formData)) {
            this.setState({ selectedFields: this.getSelectedFieldsFromProps(this.props), formData: this.props.formData });
        }
    }
    getSelectedFieldsFromProps(props) {
        const { formData, schema } = props;
        const selectedFields = [];
        Object.keys(formData || {}).forEach(key => {
            const type = schema.properties[key].type;
            if (type !== "array") {
                selectedFields.push({ type, name: key, value: formData[key] });
            }
            else {
                formData[key].forEach((data, idx) => {
                    selectedFields.push({ type, name: key, idx, value: data });
                });
            }
        });
        return selectedFields;
    }
    getArrayFieldNextIdx(fields, name) {
        const oldIndexes = fields.filter(f => f.name === name).map(f => (f.type === "array" ? f.idx : -1));
        return Math.max(...oldIndexes, -1) + 1;
    }
    render() {
        const SchemaField = this.props.registry.fields.SchemaField;
        const { schema, uiSchema, idSchema, errorSchema, formData = {}, required, disabled, readonly, formContext: { Label, translations, uiSchemaContext } } = this.props;
        const { addFieldPlaceholder = `${translations.AddField}`, confirmDelete = uiSchemaContext.confirmDelete } = (0, utils_1.getUiOptions)(uiSchema);
        const childProps = this.state.selectedFields.map(field => {
            let childSchema = schema.properties[field.name];
            let childUiSchema = uiSchema[field.name] || {};
            let childIdSchema = idSchema[field.name] || { $id: `${idSchema.$id}_${field.name}` };
            let childErrorSchema = errorSchema[field.name] || {};
            let childFormData = formData[field.name];
            if (field.type === "array" && childSchema.type === "array") {
                childSchema = childSchema.items;
                childIdSchema = Object.assign(Object.assign({}, childIdSchema), { $id: `${childIdSchema.$id}_${field.idx}` });
                childErrorSchema = childErrorSchema[field.idx] || {};
                childFormData = childFormData === null || childFormData === void 0 ? void 0 : childFormData[field.idx];
            }
            return {
                schema: childSchema,
                uiSchema: Object.assign(Object.assign({}, childUiSchema), { "ui:title": "", "ui:widget": "InputGroupWidget", "ui:options": Object.assign({ "inputGroupText": schema.properties[field.name].title || field.name, "className": "condensed-object-field-input-group" }, (childUiSchema["ui:options"] || {})) }),
                idSchema: childIdSchema,
                errorSchema: childErrorSchema,
                formData: childFormData
            };
        });
        const selectableFieldEnums = Object.keys(schema.properties).filter(prop => schema.properties[prop].type === "array" || !this.state.selectedFields.some(field => field.name === prop)).map(prop => ({
            value: prop,
            label: schema.properties[prop].title || prop,
        }));
        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 }, onChange: this.onSelectFieldChange, includeEmpty: true, schema: {}, id: `${idSchema.$id}_field_select`, formContext: this.props.formContext, disabled: this.props.disabled, readonly: this.props.readonly })));
    }
}
CondensedObjectField.propTypes = {
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object
};
exports.default = CondensedObjectField;
