"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 PropTypes = __importStar(require("prop-types"));
const utils_1 = require("@rjsf/utils");
const utils_2 = require("../../utils");
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
const functionPropType = PropTypes.shape({
    "ui:field": PropTypes.string.isRequired,
    "ui:options": PropTypes.object
});
let UiFieldMapperArrayField = class UiFieldMapperArrayField extends React.Component {
    static getName() { return "UiFieldMapperArrayField"; }
    constructor(props) {
        super(props);
        this.updateChildProps = (props) => {
            (props.formData || []).forEach((item, idx) => {
                const currentFieldProps = this.childProps[idx];
                const nextFieldProps = this.getFieldPropsForIdx(props, idx);
                if (!(0, utils_1.deepEquals)([currentFieldProps, nextFieldProps])) {
                    this.functionOutputProps[idx] = this.applyFunctionsToChildProps(props, nextFieldProps);
                    this.childProps[idx] = nextFieldProps;
                }
            });
        };
        this.getFieldPropsForIdx = (props, idx) => {
            return Object.assign(Object.assign({}, props), { schema: props.schema.items, uiSchema: (props.uiSchema.uiSchema || props.uiSchema).items, idSchema: props.idSchema, formData: (props.formData || [])[idx], errorSchema: (props.errorSchema || {})[idx] || {}, onChange: formData => {
                    this.tmpItemFormData = formData;
                } });
        };
        this.applyFunctionsToChildProps = (props, childProps) => {
            let { functions } = (0, utils_2.getUiOptions)(props.uiSchema);
            return ((Array.isArray(functions)) ? functions : [functions]).reduce((_props, { "ui:field": uiField, "ui:options": uiOptions }) => {
                const _a = _props.uiSchema || {}, { "ui:functions": uiFunctions, uiSchema, "ui:field": origUiField, "ui:options": origUiOptions, "ui:settings": origUiSettings } = _a, _propsUiSchema = __rest(_a, ["ui:functions", "uiSchema", "ui:field", "ui:options", "ui:settings"]);
                _props = Object.assign(Object.assign({}, _props), { uiSchema: Object.assign(Object.assign({}, _propsUiSchema), { "ui:field": uiField, "ui:options": uiOptions }) });
                const { state = {} } = new props.registry.fields[uiField](_props);
                return Object.assign(Object.assign(Object.assign({}, _props), state), { uiSchema: Object.assign(Object.assign(Object.assign({}, _props.uiSchema), state.uiSchema), { "ui:functions": uiFunctions, "ui:field": origUiField, "ui:options": origUiOptions, "ui:settings": origUiSettings, uiSchema }) });
            }, childProps);
        };
        this.getFunctionOutputForIdx = (props, idx) => {
            return this.applyFunctionsToChildProps(props, this.getFieldPropsForIdx(props, idx));
        };
        this.onChange = (formData) => {
            this.props.onChange(formData.map((item, idx) => {
                if (!(0, utils_1.deepEquals)(item, (this.props.formData || [])[idx])) {
                    const output = this.functionOutputProps[idx] || this.getFunctionOutputForIdx(this.props, idx);
                    output.onChange(item); // Will trigger child instance onChange, which will set this.tmpItemFormData.
                    return this.tmpItemFormData;
                }
                return item;
            }));
        };
        this.childProps = [];
        this.functionOutputProps = [];
        this.updateChildProps(props);
    }
    UNSAFE_componentWillReceiveProps(props) {
        this.updateChildProps(props);
        this.setState(this.getStateFromProps(props));
    }
    getStateFromProps(props, origProps) {
        const templateOutput = this.functionOutputProps && this.functionOutputProps.length ?
            this.functionOutputProps[0] :
            this.getFunctionOutputForIdx(origProps, undefined);
        const addBaseErrors = (errorSchema) => (props.errorSchema || {}).__errors
            ? Object.assign(Object.assign({}, errorSchema), { __errors: props.errorSchema.__errors }) : errorSchema;
        const schema = Object.assign(Object.assign({}, props.schema), { items: templateOutput.schema });
        const state = {
            schema,
            uiSchema: Object.assign(Object.assign({}, props.uiSchema), { items: Object.assign(Object.assign({}, props.uiSchema.items), templateOutput.uiSchema) }),
            formData: (props.formData || []).map((item, idx) => this.functionOutputProps[idx].formData),
            idSchema: templateOutput.idSchema,
            errorSchema: addBaseErrors(Object.keys((props.errorSchema || {})).reduce((errorSchema, idx) => {
                if (!this.functionOutputProps[idx])
                    return errorSchema;
                errorSchema[idx] = this.functionOutputProps[idx].errorSchema;
                return errorSchema;
            }, {})),
            formContext: templateOutput.formContext,
            registry: templateOutput.registry,
            onChange: this.onChange
        };
        return state;
    }
};
UiFieldMapperArrayField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            functions: PropTypes.oneOfType([
                PropTypes.arrayOf(functionPropType),
                functionPropType
            ])
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array"])
    }).isRequired,
    formData: PropTypes.array
};
UiFieldMapperArrayField = __decorate([
    VirtualSchemaField_1.default
], UiFieldMapperArrayField);
exports.default = UiFieldMapperArrayField;
