"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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 __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 });
const React = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const PropTypes = __importStar(require("prop-types"));
const utils_1 = require("../../utils");
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
const TitleField_1 = __importDefault(require("../templates/TitleField"));
const components_1 = require("../components");
const Context_1 = __importDefault(require("../../Context"));
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const ArrayFieldTemplate_1 = require("../templates/ArrayFieldTemplate");
const getOptions = (options) => {
    const { sectionField = "/section", rowDefinerField = "/units/%{row}/identifications/0/taxonVerbatim", rowDefinerFields = [
        "/units/%{row}/identifications/0/taxonID"
    ], rowValueField = "/units/%{row}/individualCount", } = options;
    return Object.assign(Object.assign({}, options), { sectionField, rowDefinerField, rowDefinerFields, rowValueField });
};
const hideFields = (schema, uiSchema, fields) => fields.reduce((_uiSchema, field) => (0, utils_1.updateSafelyWithJSONPointer)(_uiSchema, { "ui:field": "HiddenField" }, (0, utils_1.uiSchemaJSONPointer)(schema, field.replace("%{row}", "0"))), uiSchema);
const walkUiOrder = (schema, uiSchema, pathToShouldBeLast) => {
    let [prop, ...next] = pathToShouldBeLast.split("/").filter(s => !(0, utils_1.isEmptyString)(s));
    if (!prop) {
        return uiSchema;
    }
    const nextPath = `/${next.join("/")}`;
    const nextSchema = (0, utils_1.parseSchemaFromFormDataPointer)(schema, prop);
    const nextUiSchema = (0, utils_1.parseUiSchemaFromFormDataPointer)(uiSchema, prop);
    if (!isNaN(prop)) {
        return Object.assign(Object.assign({}, uiSchema), { items: walkUiOrder(nextSchema, nextUiSchema, nextPath) });
    }
    if (schema.items && schema.items.properties) {
        return Object.assign(Object.assign({}, uiSchema), { items: Object.assign(Object.assign({}, (uiSchema.items || {})), { [prop]: walkUiOrder(nextSchema, nextUiSchema, nextPath), "ui:order": ["*", prop] }) });
    }
    if (schema.properties) {
        return Object.assign(Object.assign({}, uiSchema), { [prop]: walkUiOrder(nextSchema, nextUiSchema, nextPath), "ui:order": ["*", prop] });
    }
};
const walkFieldTemplate = (schema, uiSchema = {}, template) => {
    if (schema.items && schema.items.properties) {
        return Object.assign(Object.assign({}, uiSchema), { items: walkFieldTemplate(schema.items, uiSchema.items, template) });
    }
    if (schema.properties) {
        return Object.assign(Object.assign(Object.assign({}, uiSchema), { "ui:ObjectFieldTemplate": template }), Object.keys(schema.properties).reduce((props, prop) => (Object.assign(Object.assign({}, props), { [prop]: walkFieldTemplate(schema.properties[prop], uiSchema[prop], template) })), uiSchema.properties));
    }
    return uiSchema;
};
const InvisibleTitle = (props) => {
    const uiSchema = Object.assign(Object.assign({}, (props.uiSchema || {})), { "ui:options": Object.assign(Object.assign({}, (0, utils_1.getUiOptions)(props.uiSchema)), { titleClassName: "hidden-title-text" }) });
    return React.createElement(TitleField_1.default, Object.assign({}, props, { uiSchema: uiSchema }));
};
const NoLineBreakTitle = (props) => {
    const uiSchema = Object.assign(Object.assign({}, (props.uiSchema || {})), { "ui:options": Object.assign(Object.assign({}, (0, utils_1.getUiOptions)(props.uiSchema)), { titleClassName: "no-line-break" }) });
    return React.createElement(TitleField_1.default, Object.assign({}, props, { uiSchema: uiSchema }));
};
const invisibleStyle = { visibility: "hidden" };
let SectionArrayField = class SectionArrayField extends React.Component {
    constructor(props) {
        super(props);
        // Assume that options don't change.
        this.arrayKeyFunctions = _arrayKeyFunctions(getOptions(this.getUiOptions()));
    }
    static getName() { return "SectionArrayField"; }
    getStateFromProps(props) {
        const { uiSchema, schema, registry } = props;
        const { sectionField, rowDefinerField } = getOptions(this.getUiOptions());
        const formContext = Object.assign(Object.assign({}, props.formContext), { Label: () => null, this: this, originalUiSchema: uiSchema, errorSchema: props.errorSchema, errorsAsPopup: true });
        let _uiSchema = hideFields(schema, Object.assign(Object.assign({}, uiSchema), { "ui:ArrayFieldTemplate": SectionArrayFieldTemplate }), [sectionField, rowDefinerField]);
        const [containerPointer] = rowDefinerField.split("%{row}");
        _uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(_uiSchema, false, `/${(0, utils_1.uiSchemaJSONPointer)(schema, containerPointer)}/ui:options/removable`);
        _uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(_uiSchema, [{ fn: "add", className: "invisible" }], `/${(0, utils_1.uiSchemaJSONPointer)(schema, containerPointer)}/ui:options/buttons`);
        _uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(_uiSchema, containerArrayKeyFunctions, `/${(0, utils_1.uiSchemaJSONPointer)(schema, containerPointer)}/ui:options/arrayKeyFunctions`);
        _uiSchema = walkFieldTemplate(schema, _uiSchema, NoLabelsObjectFieldTemplate);
        //_uiSchema = updateSafelyWithJSONPointer(_uiSchema, {"ui:functions": [{"ui:field": "SingleItemArrayField"}, ...currentUiFunctions], ...contentUiSchema }, uiSchemaJSONPointer(schema, containerPointer));
        _uiSchema = walkUiOrder(schema, _uiSchema, rowDefinerField.replace("%{row}", 0));
        _uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(_uiSchema, this.arrayKeyFunctions, "/ui:options/arrayKeyFunctions");
        _uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(_uiSchema, true, "/ui:options/keepPropFocusOnNavigate");
        return {
            uiSchema: _uiSchema,
            formContext,
            registry: Object.assign(Object.assign({}, registry), { formContext, templates: Object.assign(Object.assign({}, registry.templates), { TitleFieldTemplate: InvisibleTitle }) })
        };
    }
};
SectionArrayField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({})
    }),
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array"])
    }).isRequired,
    formData: PropTypes.array
};
SectionArrayField = __decorate([
    VirtualSchemaField_1.default
], SectionArrayField);
exports.default = SectionArrayField;
const Section = (_a) => {
    var { children, style } = _a, rest = __rest(_a, ["children", "style"]);
    return React.createElement("div", Object.assign({ style: style || { flexGrow: 1, width: 0, flexBasis: 0, minWidth: 1 } }, rest), children);
};
const emptyObj = {};
const doNothing = () => { };
const columnStyle = { display: "flex", flexDirection: "column" };
const SectionContent = ({ delete: _delete = React.createElement(components_1.DeleteButton, { style: invisibleStyle, className: "horizontally-centered", translations: emptyObj, onClick: doNothing }), sectionSum = React.createElement("strong", { style: invisibleStyle }, "hidden"), sectionLabel = React.createElement("legend", { style: invisibleStyle }, "hidden"), content }) => (React.createElement("div", { style: columnStyle },
    _delete,
    sectionSum,
    sectionLabel,
    content));
let SectionArrayFieldTemplate = class SectionArrayFieldTemplate extends React.Component {
    constructor(props) {
        super(props);
        this.containerRef = React.createRef();
        this.onFocuses = [];
        this.getOnFocus = (i) => () => {
            this.props.formContext.globals[`${this.props.idSchema.$id}.activeIdx`] = i + ((0, utils_1.getUiOptions)(this.props.uiSchema).startIdx || 0);
        };
        this.getElemsForRowIdx = (rowIdx) => {
            const { rowValueField, rowDefinerField } = getOptions((0, utils_1.getUiOptions)(this.props.uiSchema));
            return [
                `${this.props.idSchema.$id}_0_${(0, utils_1.JSONPointerToId)(rowDefinerField.replace("%{row}", rowIdx))}`,
                ...this.props.formData.map((_, idx) => `${this.props.idSchema.$id}_${idx}_${(0, utils_1.JSONPointerToId)(rowValueField.replace("%{row}", rowIdx))}`)
            ].map(id => document.getElementById(id));
        };
        this.onContainerFocus = (e) => {
            const { id } = e.target;
            const [rowIdx] = getIdxsFromId(this.props.idSchema, getOptions((0, utils_1.getUiOptions)(this.props.uiSchema)), id);
            if (rowIdx !== undefined) {
                this.focusedRowIdx = rowIdx;
                this.getElemsForRowIdx(rowIdx).forEach(elem => {
                    if (elem) {
                        elem.className += " input-highlight";
                    }
                });
            }
        };
        this.onContainerBlur = () => {
            if (this.focusedRowIdx !== undefined) {
                this.getElemsForRowIdx(this.focusedRowIdx).forEach(elem => {
                    if (elem) {
                        elem.className = elem.className.replace(" input-highlight", "");
                    }
                });
            }
        };
        this.getAddButtonElem = () => {
            return (0, react_dom_1.findDOMNode)(this.addButtonRef.current);
        };
        this.showAddSection = () => {
            this.setState({ showAddSection: true }, () => {
                setTimeout(() => {
                    (0, react_dom_1.findDOMNode)(this.sectionInputRef.current).focus();
                });
            });
        };
        this.hideAddSection = () => {
            this.setState({ showAddSection: false, newSection: undefined });
        };
        this.getAddSectionPopup = () => {
            const { translations } = this.props.formContext;
            const { newSection = "" } = this.state;
            const { Row, Col } = this.context.theme;
            return (React.createElement("div", { className: "laji-form" },
                React.createElement("div", null,
                    React.createElement("strong", null, translations.AddNewSection)),
                React.createElement(Row, null,
                    React.createElement(Col, { xs: 3 },
                        React.createElement("label", { className: "row-height not-strong", htmlFor: `${this.props.idSchema.$id}-section-input` },
                            translations.Number,
                            ":")),
                    React.createElement(Col, { xs: 9 },
                        React.createElement("input", { className: "form-control", id: `${this.props.idSchema.$id}-section-input`, type: "text", value: newSection, onChange: this.onNewSectionChange, onKeyDown: this.onNewSectionKeyDown, ref: this.sectionInputRef }))),
                React.createElement("div", null, translations.EnterNewSectionNumber),
                React.createElement(components_1.Button, { disabled: !this.sectorIsValid(newSection), onClick: this.addSection }, translations.Add),
                React.createElement(components_1.Button, { onClick: this.hideAddSection, variant: "default" }, translations.Cancel)));
        };
        this.sectorIsValid = (newSection) => {
            const { sectionField } = getOptions((0, utils_1.getUiOptions)(this.props.uiSchema));
            const existingNumbers = this.props.formData.map(item => "" + (0, utils_1.parseJSONPointer)(item, sectionField));
            return !(isNaN(parseInt(newSection)) || parseInt(newSection) < 0 || parseInt(newSection) > 50 || existingNumbers.includes(newSection));
        };
        this.onNewSectionChange = (e) => {
            this.setState({ newSection: e.target.value.replace(/[^0-9/-]/g, "") });
        };
        this.onNewSectionKeyDown = (e) => {
            if (e.key === "Enter") {
                if (!this.sectorIsValid(this.state.newSection)) {
                    return;
                }
                this.addSection();
                this.hideAddSection();
                e.stopPropagation();
            }
        };
        this.addSection = () => {
            const { registry, formContext, uiSchema, schema } = this.props;
            const { newSection } = this.state;
            const { rowDefinerField, rowDefinerFields, sectionField } = getOptions((0, utils_1.getUiOptions)(uiSchema));
            const [containerPointer] = rowDefinerField.split("/%{row}");
            const copiedRowDefinerData = ((0, utils_1.parseJSONPointer)(this.props.formData[0] || {}, containerPointer) || []).reduce((result, item, idx) => {
                return [rowDefinerField, ...rowDefinerFields].reduce((_result, field) => {
                    const [_, parsedField] = field.split("/%{row}");
                    return (0, utils_1.updateFormDataWithJSONPointer)({
                        schema: schema.items,
                        formData: _result,
                        registry
                    }, (0, utils_1.parseJSONPointer)(item, parsedField), field.replace(/%{row}/g, idx));
                }, result);
            }, (0, utils_1.getDefaultFormState)(schema.items));
            const tmpIdTree = formContext.services.ids.getRelativeTmpIdTree(this.props.idSchema.$id);
            const _item = copiedRowDefinerData;
            let [item] = (0, utils_1.addLajiFormIds)(_item, tmpIdTree, this.props.idSchema.$id);
            item = (0, utils_1.updateFormDataWithJSONPointer)({ schema: schema.items, formData: item, registry }, parseInt(newSection), sectionField);
            const items = [...this.props.formData, item];
            const idx = items.findIndex(i => i === item);
            const idToFocus = `${this.props.idSchema.$id}_${idx}`;
            let { idToScrollAfterAdd = `${this.props.idSchema.$id}-add-section` } = (0, utils_1.getUiOptions)(uiSchema || {});
            (0, Context_1.default)(formContext.contextId).idToFocus = idToFocus;
            (0, Context_1.default)(formContext.contextId).idToScroll = idToScrollAfterAdd;
            formContext.this.props.onChange(items);
            this.hideAddSection();
        };
        this.onRowDefinerChange = formData => {
            const { rowDefinerField, rowDefinerFields } = getOptions((0, utils_1.getUiOptions)(this.props.uiSchema));
            const [containerPointer] = rowDefinerField.split("%{row}");
            const rowDefinerItemIdsToContainerIdxs = ((0, utils_1.parseJSONPointer)(this.props.formData[0] || {}, containerPointer) || []).reduce((map, item, idx) => {
                map[(0, utils_1.getUUID)(item)] = idx;
                return map;
            }, {});
            const tmpIdTree = this.props.formContext.services.ids.getRelativeTmpIdTree(`${this.props.idSchema.$id}_${(0, utils_1.JSONPointerToId)(containerPointer.substr(0, containerPointer.length - 1))}`);
            const oldIds = (0, utils_1.getAllLajiFormIdsDeeply)(this.props.formData, tmpIdTree);
            let ids = {};
            const _formData = this.props.formData.map((item, containerIdx) => {
                const items = (0, utils_1.parseJSONPointer)(formData, containerPointer).map((unit, idx) => {
                    let rowDefinerItem = (0, utils_1.parseJSONPointer)(item, `${containerPointer}/${rowDefinerItemIdsToContainerIdxs[(0, utils_1.getUUID)(unit)]}`);
                    if (!rowDefinerItem) {
                        // If container is first and it has UUID, it's an item added to the definer column. It has a UUID already, so 
                        // we don't define it again, or else it will be rendered again and won't be autofocused properly.
                        const [_rowDefinerItem, _ids] = containerIdx === 0 && (0, utils_1.getUUID)(unit)
                            ? (0, utils_1.addLajiFormIds)(unit, tmpIdTree)
                            : (0, utils_1.addLajiFormIds)(this.props.formContext.utils.filterItemIdsDeeply(unit, this.props.idSchema.$id), tmpIdTree, false);
                        rowDefinerItem = _rowDefinerItem;
                        ids = Object.assign(Object.assign({}, ids), _ids);
                    }
                    const updatedUnit = [rowDefinerField, ...rowDefinerFields].reduce((updatedNewUnit, field) => {
                        const [_, contentPointer] = field.split("%{row}");
                        const pointer = field.replace("%{row}", idx);
                        const value = (0, utils_1.parseJSONPointer)(formData, pointer);
                        return (0, utils_1.updateFormDataWithJSONPointer)({
                            schema: (0, utils_1.parseSchemaFromFormDataPointer)(this.props.schema.items, containerPointer).items,
                            formData: updatedNewUnit,
                            registry: this.props.registry
                        }, value, contentPointer);
                    }, rowDefinerItem);
                    return (0, utils_1.addLajiFormIds)(updatedUnit, tmpIdTree, false)[0];
                });
                return (0, utils_1.updateFormDataWithJSONPointer)({
                    schema: this.props.schema.items,
                    formData: item,
                    registry: this.props.registry
                }, items, containerPointer);
            });
            this.props.formContext.this.props.onChange(_formData);
            Object.keys(oldIds).forEach(id => {
                if (!ids[id]) {
                    this.props.formContext.services.submitHooks.remove(id);
                }
            });
        };
        this.addButtonRef = React.createRef();
        this.sectionInputRef = React.createRef();
    }
    render() {
        return (React.createElement("div", { style: { display: "flex", width: "100%" }, ref: this.containerRef, onFocus: this.onContainerFocus, onBlur: this.onContainerBlur, tabIndex: 0 },
            React.createElement(Section, { key: "definer", style: { flexGrow: "initial", maxWidth: 200 }, id: `${this.props.idSchema.$id}-section-definer` }, this.renderRowDefinerColumn()),
            this.renderSections(),
            React.createElement(Section, { key: "sums", className: "bg-info", style: { maxWidth: 75 } }, this.renderRowDefinerSumColumn()),
            React.createElement(Section, { key: "deletes", style: { flexGrow: "initial", maxWidth: 143 } }, this.renderRowDefinerDeleteColumn())));
    }
    renderRowDefinerColumn() {
        const { formData, uiSchema, schema, registry } = this.props;
        const { rowDefinerField, rowValueField, sectionField } = getOptions((0, utils_1.getUiOptions)(uiSchema));
        const [containerPointer] = rowDefinerField.split("/%{row}");
        const { SchemaField } = this.props.registry.fields;
        const { originalUiSchema } = this.props.formContext;
        const _schema = schema.items;
        const _formData = formData[0];
        let __uiSchema = hideFields(schema, originalUiSchema, [rowValueField, sectionField]);
        __uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(__uiSchema.items, false, `${containerPointer}/ui:options/removable`);
        __uiSchema = walkUiOrder(schema.items, __uiSchema, rowDefinerField.replace("%{row}", 0));
        __uiSchema = walkFieldTemplate(schema.items, __uiSchema, RowDefinerObjectFieldTemplate);
        __uiSchema = walkUiOrder(schema.items, __uiSchema, `${containerPointer}/0/identifications`);
        const formContext = Object.assign(Object.assign({}, this.props.formContext), { rowDefinerField, sectionPointer: (0, utils_1.idSchemaIdToJSONPointer)(this.props.idSchema.$id) });
        const idSchema = this.props.registry.schemaUtils.toIdSchema(this.props.schema.items, `${this.props.idSchema.$id}_0`);
        const sectionLabel = (React.createElement(components_1.Affix, { className: "background", containerRef: this.containerRef, topOffset: this.props.formContext.topOffset, bottomOffset: this.props.formContext.bottomOffset },
            React.createElement("legend", null, this.props.formContext.translations.Section)));
        const sectionSum = React.createElement("strong", null, this.props.formContext.translations.SectionSum);
        const content = (React.createElement(SchemaField, Object.assign({}, this.props, { schema: _schema, uiSchema: __uiSchema, formData: _formData, idSchema: idSchema, onChange: this.onRowDefinerChange, registry: Object.assign(Object.assign({}, registry), { formContext, templates: Object.assign(Object.assign({}, registry.templates), { TitleFieldTemplate: NoLineBreakTitle }) }), formContext: formContext, errorSchema: this.props.formContext.errorSchema[0] || {} })));
        return React.createElement(SectionContent, { content: content, sectionLabel: sectionLabel, sectionSum: sectionSum });
    }
    renderSections() {
        const { sectionField, rowValueField } = getOptions((0, utils_1.getUiOptions)(this.props.uiSchema));
        return (this.props.formData || []).map((item, idx) => {
            if (!this.props.items[idx]) {
                return null;
            }
            const { children, hasRemove, index, disabled, readonly, onDropIndexClick } = this.props.items[idx];
            const del = hasRemove && (React.createElement(components_1.DeleteButton, { id: `${this.props.idSchema.$id}_${index}`, disabled: disabled || readonly, translations: this.props.formContext.translations, confirm: this.props.formContext.uiSchemaContext.confirmDelete, onClick: onDropIndexClick(index), className: "horizontally-centered" }));
            const sectionLabel = (React.createElement(components_1.Affix, { className: index % 2 ? "background" : " darker", containerRef: this.containerRef, topOffset: this.props.formContext.topOffset, bottomOffset: this.props.formContext.bottomOffset },
                React.createElement("legend", { className: "horizontally-centered" }, (0, utils_1.parseJSONPointer)(this.props.formData[index], sectionField))));
            const [arr, field] = rowValueField.split("/%{row}");
            const sum = ((0, utils_1.parseJSONPointer)(item, arr) || []).reduce((sum, item) => sum + ((0, utils_1.parseJSONPointer)(item, field) || 0), 0);
            const sectionSum = (React.createElement("strong", { className: "horizontally-centered text-muted" }, sum));
            return (React.createElement(Section, { onFocus: this.getOnFocus(idx), key: (0, utils_1.getUUID)(item), className: index % 2 ? undefined : "darker", id: `${this.props.idSchema.$id}_${idx}-section` },
                React.createElement(SectionContent, { delete: del, sectionLabel: sectionLabel, sectionSum: sectionSum, content: children })));
        });
    }
    renderRowDefinerDeleteColumn() {
        const { schema, registry, formData } = this.props;
        const { rowDefinerField, rowValueField, sectionField } = getOptions((0, utils_1.getUiOptions)(this.props.uiSchema));
        const [containerPointer] = rowDefinerField.split("/%{row}");
        const { SchemaField } = this.props.registry.fields;
        const { originalUiSchema } = this.props.formContext;
        let _schema = schema.items;
        const _formData = formData[0];
        let __uiSchema = hideFields(schema, originalUiSchema, [rowValueField, sectionField]);
        __uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(__uiSchema, [{ fn: "add", className: "invisible" }], `/${(0, utils_1.uiSchemaJSONPointer)(schema, containerPointer)}/ui:options/buttons`);
        __uiSchema = walkUiOrder(schema.items, __uiSchema.items, rowDefinerField.replace("%{row}", 0));
        __uiSchema = walkFieldTemplate(schema.items, __uiSchema, InvisibleLabelObjectFieldTemplate);
        const formContext = Object.assign(Object.assign({}, this.props.formContext), { containerPointer, sectionPointer: (0, utils_1.idSchemaIdToJSONPointer)(this.props.idSchema.$id) });
        const { Overlay, Popover, Glyphicon } = this.context.theme;
        const add = (React.createElement(React.Fragment, null,
            React.createElement(components_1.Affix, { containerRef: this.containerRef, topOffset: this.props.formContext.topOffset, bottomOffset: this.props.formContext.bottomOffset },
                React.createElement(components_1.Button, { id: `${this.props.idSchema.$id}-add`, onClick: this.showAddSection, style: { whiteSpace: "nowrap", padding: "3.5px 12px" }, ref: this.addButtonRef },
                    React.createElement(Glyphicon, { glyph: "plus" }),
                    " ",
                    this.props.formContext.translations.AddSection)),
            (this.state || {}).showAddSection &&
                React.createElement(Overlay, { show: true, placement: "left", rootClose: true, onHide: this.hideAddSection, target: this.getAddButtonElem },
                    React.createElement(Popover, { id: `${this.props.id}-show-add-section` }, this.getAddSectionPopup()))));
        const delButtons = (React.createElement(SchemaField, Object.assign({}, this.props, { schema: _schema, uiSchema: __uiSchema, formData: _formData, onChange: this.onRowDefinerChange, registry: Object.assign(Object.assign({}, registry), { formContext, fields: Object.assign(Object.assign({}, registry.fields), { TitleFieldTemplate: InvisibleTitle }) }), formContext: formContext })));
        return React.createElement(SectionContent, { delete: add, content: delButtons });
    }
    renderRowDefinerSumColumn() {
        const { schema, registry, formData } = this.props;
        const { rowDefinerField, rowDefinerFields, rowValueField, sectionField } = getOptions((0, utils_1.getUiOptions)(this.props.uiSchema));
        const [containerPointer, valueField] = rowValueField.split("/%{row}");
        const { SchemaField } = this.props.registry.fields;
        const { originalUiSchema } = this.props.formContext;
        let _schema = (0, utils_1.updateSafelyWithJSONPointer)(schema.items, { type: "integer" }, `/properties/${containerPointer}/items/properties/sum`);
        let _formData = formData[0];
        const sums = formData.reduce((sums, item) => {
            ((0, utils_1.parseJSONPointer)(item, containerPointer) || []).forEach((definerItem, idx) => {
                sums[idx] = (sums[idx] || 0) + ((0, utils_1.parseJSONPointer)(definerItem, valueField) || 0);
            });
            return sums;
        }, []);
        sums.forEach((sum, idx) => {
            _formData = (0, utils_1.updateSafelyWithJSONPointer)(_formData || {}, sum, `${containerPointer}/${idx}/sum`);
        });
        let containerUiSchema = Object.keys((0, utils_1.parseSchemaFromFormDataPointer)(_schema, containerPointer).items.properties).reduce((uiSchema, field) => {
            if (field === "sum") {
                return uiSchema;
            }
            return Object.assign(Object.assign({}, uiSchema), { [field]: { "ui:field": "HiddenField" } });
        }, (0, utils_1.parseUiSchemaFromFormDataPointer)(originalUiSchema, containerPointer).items);
        let __uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(originalUiSchema, containerUiSchema, `/items/${containerPointer}/items`);
        __uiSchema = hideFields(schema, __uiSchema, [rowValueField, sectionField, rowDefinerField, ...rowDefinerFields]);
        __uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(__uiSchema.items, Object.assign(Object.assign({}, (0, utils_1.parseJSONPointer)(__uiSchema.items, `${containerPointer}/ui:options`)), { removable: false, buttons: [{ fn: "add", className: "invisible" }] }), `${containerPointer}/ui:options`);
        __uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(__uiSchema, {
            "ui:widget": "PlainTextWidget",
            "ui:options": { strong: true, centered: true }
        }, `${containerPointer}/items/sum`);
        __uiSchema = walkFieldTemplate(schema.items, __uiSchema, SumObjectFieldTemplate);
        __uiSchema = walkUiOrder(schema.items, __uiSchema, rowDefinerField.replace("%{row}", 0));
        const formContext = Object.assign(Object.assign({}, this.props.formContext), { containerPointer, sectionPointer: (0, utils_1.idSchemaIdToJSONPointer)(this.props.idSchema.$id), rowValueField,
            rowDefinerField });
        const sumLabel = (React.createElement(components_1.Affix, { containerRef: this.containerRef, topOffset: this.props.formContext.topOffset, bottomOffset: this.props.formContext.bottomOffset },
            React.createElement("legend", { className: "bg-info horizontally-centered" }, this.props.formContext.translations.Sum)));
        const content = (React.createElement(SchemaField, Object.assign({}, this.props, { schema: _schema, uiSchema: __uiSchema, formData: _formData, onChange: this.onRowDefinerChange, registry: Object.assign(Object.assign({}, registry), { formContext, fields: Object.assign(Object.assign({}, registry.fields), { TitleFieldTemplate: InvisibleTitle }) }), formContext: formContext })));
        return React.createElement(SectionContent, { sectionLabel: sumLabel, content: content });
    }
};
SectionArrayFieldTemplate.contextType = ReactContext_1.default;
SectionArrayFieldTemplate = __decorate([
    ArrayFieldTemplate_1.handlesArrayKeys
], SectionArrayFieldTemplate);
const withoutItemPointers = pointer => pointer.replace(/\/([0-9]+|%{row})/g, "");
const InvisibleLabelObjectFieldTemplate = (props) => {
    const { containerPointer } = props.formContext;
    const pointer = (0, utils_1.idSchemaIdToJSONPointer)(props.idSchema.$id);
    const containerPointerWithoutItemPointers = withoutItemPointers(containerPointer);
    const pointerWithoutItemPointers = withoutItemPointers(pointer);
    return props.properties.map(prop => {
        const propUiSchema = props.uiSchema[prop.name] || {};
        if (propUiSchema["ui:field"] === "HiddenField" || propUiSchema["ui:widget"] === "HiddenWidget") {
            return null;
        }
        if (containerPointerWithoutItemPointers.startsWith(pointerWithoutItemPointers.replace(props.formContext.sectionPointer, "") + "/" + prop.name)) {
            return React.createElement(React.Fragment, { key: prop.name }, prop.content);
        }
        return React.createElement("div", { key: prop.name, className: "form-group row-height" },
            React.createElement("label", null));
    });
};
const SumObjectFieldTemplate = (props) => {
    const { containerPointer } = props.formContext;
    const pointer = (0, utils_1.idSchemaIdToJSONPointer)(props.idSchema.$id);
    const containerPointerWithoutItemPointers = withoutItemPointers(containerPointer);
    const pointerWithoutItemPointers = withoutItemPointers(pointer);
    return props.properties.map(prop => {
        const propUiSchema = props.uiSchema[prop.name] || {};
        if (propUiSchema["ui:field"] === "HiddenField" || propUiSchema["ui:widget"] === "HiddenWidget") {
            return null;
        }
        if ((containerPointerWithoutItemPointers.startsWith(pointerWithoutItemPointers.replace(props.formContext.sectionPointer, "") + "/" + prop.name))
            || prop.name === "sum") {
            return React.createElement(React.Fragment, { key: prop.name }, prop.content);
        }
        return React.createElement("div", { key: prop.name, className: "form-group row-height " + prop.name },
            React.createElement("label", null));
    });
};
const NoLabelsObjectFieldTemplate = (props) => {
    return props.properties.map(prop => prop.content);
};
const RowDefinerObjectFieldTemplate = (props) => {
    const pointer = (0, utils_1.idSchemaIdToJSONPointer)(props.idSchema.$id);
    const rowDefinerFieldWithoutItemPointers = withoutItemPointers(props.formContext.rowDefinerField);
    const pointerWithoutItemPointers = withoutItemPointers(pointer);
    return props.properties.map(prop => {
        const propUiSchema = props.uiSchema[prop.name] || {};
        if (propUiSchema["ui:field"] === "HiddenField" || propUiSchema["ui:widget"] === "HiddenWidget") {
            return null;
        }
        if ((rowDefinerFieldWithoutItemPointers.startsWith(pointerWithoutItemPointers.replace(props.formContext.sectionPointer, "") + "/" + prop.name))) {
            return React.createElement(React.Fragment, { key: prop.name }, prop.content);
        }
        const title = (props.uiSchema[prop.name] || {})["ui:title"] || props.schema.properties[prop.name].title || prop.name;
        return React.createElement("div", { key: prop.name, className: "form-group row-height" },
            React.createElement("label", null, title));
    });
};
const getIdxsFromId = (idSchema, options, _id) => {
    const { rowDefinerField } = options;
    const id = idSchema.$id;
    const sectionIdx = _id.match(new RegExp(`${id}_(\\d+)`))
        && !_id.match(new RegExp(`${id}_\\d+_${(0, utils_1.JSONPointerToId)(rowDefinerField.replace("%{row}", "\\d+"))}`))
        ? +_id.match(new RegExp(`${id}_(\\d+)`))[1]
        : undefined;
    const [containerPointer] = rowDefinerField.split("%{row}");
    const horizontalIdx = _id.match(new RegExp(`${id}_\\d+_${(0, utils_1.JSONPointerToId)(containerPointer)}`))
        ? +_id.match(new RegExp(`${id}_\\d+_${(0, utils_1.JSONPointerToId)(containerPointer)}(\\d+)`))[1]
        : undefined;
    return [horizontalIdx, sectionIdx];
};
const _arrayKeyFunctions = options => {
    const keyFunctions = Object.assign(Object.assign({}, ArrayFieldTemplate_1.arrayKeyFunctions), { insert: (e, props) => {
            document.getElementById(`${props.getProps().idSchema.$id}-add`).click();
        }, navigateSection: (e, { getProps, left, right, up, goOverRow }) => {
            const { rowDefinerField, rowValueField } = options;
            const currentId = getProps().formContext.utils.findNearestParentSchemaElemId(document.activeElement);
            const amount = left || up ? -1 : 1;
            const id = getProps().idSchema.$id;
            let nextId;
            const [currentRow, currentSection] = getIdxsFromId(getProps().idSchema, options, currentId);
            if (currentRow === undefined && currentSection === undefined) {
                return false;
            }
            const getNonRowSectionFieldsForSectionIdx = sectionIdx => {
                let tabbable = (0, utils_1.getTabbableFields)(document.getElementById(`${id}_${sectionIdx}-section`));
                return tabbable.filter(elem => {
                    return !elem.id.match(new RegExp((0, utils_1.JSONPointerToId)(rowValueField.replace("%{row}", "\\d+"))));
                });
            };
            const goOverToNonRowLogic = (currentProp, reverse = true, last = true) => {
                let tabbableInSection = (0, utils_1.getTabbableFields)(document.getElementById(`${id}_${last ? getProps().formData.length - 1 : 0}-section`));
                if (reverse) {
                    tabbableInSection = tabbableInSection.reverse();
                }
                let currentPropEncountered = false;
                const elem = tabbableInSection.find(elem => {
                    if (!elem.id.match(new RegExp((0, utils_1.JSONPointerToId)(rowValueField.replace("%{row}", "\\d+"))))) {
                        if (!currentProp || currentPropEncountered) {
                            return elem;
                        }
                        if (elem.id.match(currentProp)) {
                            currentPropEncountered = true;
                        }
                    }
                });
                nextId = getProps().formContext.utils.findNearestParentSchemaElemId(elem);
            };
            if (left || right) {
                // Horizontal navigation from row definer column to row value column.
                if (right && currentSection === undefined) {
                    const idSuffix = (0, utils_1.JSONPointerToId)(rowValueField.replace("%{row}", currentRow));
                    nextId = `${id}_0_${idSuffix}`;
                    // Horizontal navigation from row value column to row definer column.
                }
                else if (left && currentSection === 0 && currentRow !== undefined) {
                    const idSuffix = (0, utils_1.JSONPointerToId)(rowDefinerField.replace("%{row}", currentRow));
                    nextId = `${id}_${currentSection}_${idSuffix}`;
                    // Horizontal navigation to next/prev row if goOverRow.
                }
                else if (right && currentSection === getProps().formData.length - 1) {
                    if (!goOverRow) {
                        return false;
                    }
                    // Horizontal navigation inside row matrix.
                    if (currentRow !== undefined) {
                        const idSuffix = (0, utils_1.JSONPointerToId)(rowDefinerField.replace("%{row}", currentRow + 1));
                        nextId = `${id}_${0}_${idSuffix}`;
                    }
                    else {
                        let tabbableInSection = getNonRowSectionFieldsForSectionIdx(getProps().formData.length - 1);
                        // Horizontal navigation inside non row section field.
                        if (currentId === getProps().formContext.utils.findNearestParentSchemaElemId(tabbableInSection[tabbableInSection.length - 1])) {
                            nextId = `${id}_0_${(0, utils_1.JSONPointerToId)(rowDefinerField.replace("%{row}", 0))}`;
                            // Horizontal navigation from non row section to row field.
                        }
                        else {
                            const currentProp = currentId.match(`${id}_${currentSection}_(.+)`)[1];
                            goOverToNonRowLogic(currentProp, false, false);
                        }
                    }
                }
                else if (left && currentSection === undefined) {
                    if (goOverRow) {
                        // Horizontal navigation from row field to non row section field.
                        if (currentRow === 0) {
                            goOverToNonRowLogic();
                            // Horizontal navigation inside row value fields.
                        }
                        else {
                            const idSuffix = (0, utils_1.JSONPointerToId)(rowValueField.replace("%{row}", currentRow - 1));
                            nextId = `${id}_${getProps().formData.length - 1}_${idSuffix}`;
                        }
                    }
                    // Horizontal navigation inside non row section fields.
                }
                else if (left && currentRow === undefined && currentSection === 0) {
                    if (goOverRow) {
                        const currentProp = currentId.match(`${id}_${currentSection}_(.+)`)[1];
                        goOverToNonRowLogic(currentProp);
                    }
                    // Horizontal navigation inside value matrix.
                }
                else {
                    const [idPrefix] = currentId.match(new RegExp(`${id}_(\\d+)`));
                    const idSuffix = currentId.replace(`${idPrefix}_`, "");
                    nextId = `${id}_${+currentSection + amount}_${idSuffix}`;
                }
            }
            else {
                // Vertical navigation.
                const containerId = currentSection !== undefined
                    ? `${id}_${currentSection}-section`
                    : `${id}-section-definer`;
                const tabbableOutsideContainer = (0, utils_1.getTabbableFields)(document.getElementById(containerId));
                const tabbableIdx = tabbableOutsideContainer.findIndex(e => e === document.activeElement);
                nextId = getProps().formContext.utils.findNearestParentSchemaElemId(tabbableOutsideContainer[tabbableIdx + amount]);
                if (nextId === "root") {
                    return true;
                }
            }
            getProps().formContext.utils.focusAndScroll(nextId);
        } });
    keyFunctions.navigate = (e, props) => {
        const { getProps, reverse } = props;
        const id = getProps().idSchema.$id;
        if (!reverse) {
            const lastSectionElems = (0, utils_1.getTabbableFields)(document.getElementById(`${id}_${getProps().formData.length - 1}-section`));
            const lastElem = lastSectionElems[lastSectionElems.length - 1];
            if (document.activeElement === lastElem) {
                return false;
            }
        }
        else {
            const { rowDefinerField } = options;
            const firstElem = (0, utils_1.getTabbableFields)(document.getElementById(`${id}_0-section`))[0];
            if (document.activeElement === firstElem) {
                const allTabbableFields = (0, utils_1.getTabbableFields)((0, react_dom_1.findDOMNode)(getProps().formContext.formRef.current));
                const matcher = new RegExp((0, utils_1.JSONPointerToId)(rowDefinerField.replace("%{row}", "\\d+")));
                const allTabbableFieldsWithoutRowDefinerInputs = allTabbableFields.filter(f => !f.id.match(matcher));
                const input = getProps().formContext.utils.getNextInputInInputs(undefined, true, allTabbableFieldsWithoutRowDefinerInputs);
                if (input) {
                    input.focus();
                }
                return true;
            }
        }
        return keyFunctions.navigateSection(e, Object.assign(Object.assign({}, props), { right: !props.reverse, left: props.reverse, goOverRow: true }));
    };
    return keyFunctions;
};
const containerArrayKeyFunctions = Object.assign(Object.assign({}, ArrayFieldTemplate_1.arrayKeyFunctions), { 
    // Disable insert, insert should bubble to section adding.
    insert: () => {
        return false;
    } });
