"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 __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 immutability_helper_1 = __importDefault(require("immutability-helper"));
const utils_1 = require("../../utils");
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
function getPropName(field, innerField, isArray) {
    return `${field}_${isArray ? "0_" : ""}${innerField}`;
}
let FlatField = class FlatField extends React.Component {
    constructor() {
        super(...arguments);
        this._onChange = (formData, schema, fields) => {
            let _fields = [], deepFields = [];
            fields.forEach(f => {
                (f.includes("_") ? deepFields : _fields).push(f);
            });
            Object.keys(formData).sort().forEach(prop => {
                if (prop.includes("_"))
                    _fields.forEach(field => {
                        if (prop.includes(`${field}_`)) {
                            const isArray = (schema.properties[field].type === "array");
                            const newItemName = prop.replace(`${field}_${isArray ? "0_" : ""}`, "");
                            const newItemBase = isArray ?
                                ((formData[field] && formData[field][0]) ? formData[field][0] : {}) :
                                (formData[field] || {});
                            const updatedItem = Object.assign(Object.assign({}, newItemBase), { [newItemName]: formData[prop] });
                            formData = Object.assign(Object.assign({}, formData), { [field]: isArray ? [updatedItem] : updatedItem });
                            formData = (0, utils_1.immutableDelete)(formData, prop);
                        }
                    });
            });
            deepFields.forEach(deepField => {
                const deepContainerName = deepField.match(/^[^_]*/)[0];
                const deepContainer = formData[deepContainerName][0] || formData[deepContainerName];
                deepField = deepField.replace(/^[^_]*_(0_)?/, "");
                const deepSchema = schema.properties[deepContainerName];
                const changedDeep = this._onChange(deepContainer, deepSchema.items || deepSchema, [deepField]);
                formData = Object.assign(Object.assign({}, formData), { [deepContainerName]: deepSchema.type === "array" ? [changedDeep] : changedDeep });
            });
            return formData;
        };
        this.onChange = (formData) => {
            const _formData = this._onChange(formData, this.props.schema, this.getUiOptions().fields);
            this.props.onChange(_formData);
        };
    }
    static getName() { return "FlatField"; }
    getStateFromProps(props, origProps) {
        const state = {
            schema: props.schema,
            uiSchema: props.uiSchema,
            errorSchema: props.errorSchema,
            formData: props.formData,
            idSchema: props.idSchema,
            onChange: this.onChange
        };
        const { fields } = this.getUiOptions();
        fields.sort().forEach(field => {
            let innerSchema = state.schema.properties[field];
            const isArray = innerSchema.type === "array";
            if (isArray)
                innerSchema = innerSchema.items;
            let { properties } = innerSchema;
            if (properties)
                Object.keys(properties).forEach(innerField => {
                    state.schema = (0, immutability_helper_1.default)(state.schema, { properties: { $merge: { [getPropName(field, innerField, isArray)]: properties[innerField] } } });
                    if (innerSchema.required && innerSchema.required.indexOf(innerField) !== -1) {
                        state.schema.required = (0, immutability_helper_1.default)(state.schema.required || [], { $push: [getPropName(field, innerField, isArray)] });
                    }
                    if (state.uiSchema[field]) {
                        if (!isArray && state.uiSchema[field][innerField]) {
                            state.uiSchema = (0, immutability_helper_1.default)(state.uiSchema, { $merge: { [getPropName(field, innerField, isArray)]: state.uiSchema[field][innerField] } });
                        }
                        else if (isArray && state.uiSchema[field].items && state.uiSchema[field].items[innerField]) {
                            state.uiSchema = (0, immutability_helper_1.default)(state.uiSchema, { $merge: { [getPropName(field, innerField, isArray)]: state.uiSchema[field].items[innerField] } });
                        }
                    }
                    state.idSchema = Object.assign(Object.assign({}, state.idSchema), { [field]: this.props.registry.schemaUtils.toIdSchema(state.schema.properties[field], `${state.idSchema.$id}_${field}`) });
                    let innerId = state.idSchema[field][innerField].$id;
                    if (isArray) {
                        innerId = innerId.replace(/(.*)_(.*)$/, "$1_0_$2");
                    }
                    state.idSchema = (0, immutability_helper_1.default)(state.idSchema, { $merge: { [getPropName(field, innerField, isArray)]: { $id: innerId } } });
                });
            state.schema.properties = (0, utils_1.immutableDelete)(state.schema.properties, field);
            state.idSchema = (0, utils_1.immutableDelete)(state.idSchema, field);
            const { "ui:order": order = [] } = state.uiSchema;
            const orderIdxs = order.reduce((obj, field, idx) => {
                obj[field] = idx;
                return obj;
            }, {});
            if (field in orderIdxs) {
                const head = order.slice(0, orderIdxs[field]);
                const tail = order.slice(orderIdxs[field] + 1);
                state.uiSchema["ui:order"] = [...head, ...Object.keys(properties).map(innerField => getPropName(field, innerField, isArray)), ...tail];
            }
            if (state.formData && state.formData[field]) {
                let innerData = state.formData[field];
                if (!innerData && state.schema.properties[field].type === "object") {
                    innerData = (0, utils_1.getDefaultFormState)(state.schema.properties[field]);
                }
                else if (!innerData && state.schema.properties[field].type === "array") {
                    innerData = [(0, utils_1.getDefaultFormState)(state.schema.properties[field].items)];
                }
                if (Array.isArray(innerData)) {
                    innerData = innerData[0];
                }
                Object.keys(innerData || {}).forEach(innerField => {
                    state.formData = Object.assign(Object.assign({}, state.formData), { [getPropName(field, innerField, isArray)]: innerData[innerField] });
                });
                state.formData = (0, utils_1.immutableDelete)(state.formData, field);
            }
            if (state.errorSchema) {
                Object.keys(state.errorSchema).forEach(errorField => {
                    if (errorField === field) {
                        if (isArray) {
                            Object.keys(state.errorSchema[errorField])
                                .filter(key => key !== "__errors")
                                .map(key => state.errorSchema[errorField][key]).forEach(error => {
                                Object.keys(error).forEach(innerError => {
                                    state.errorSchema = Object.assign(Object.assign({}, state.errorSchema), { [getPropName(field, innerError, isArray)]: Object.assign(Object.assign({}, (state.errorSchema[getPropName(field, innerError, isArray)] || {})), error[innerError]) });
                                });
                            });
                            state.errorSchema = (0, utils_1.immutableDelete)(state.errorSchema, field);
                            if (state.errorSchema[field] && state.errorSchema[field].__errors) {
                                state.errorSchema = Object.assign(Object.assign({}, state.errorSchema), { __errors: state.errorSchema[field].__errors });
                            }
                        }
                        else {
                            Object.keys(state.errorSchema[errorField]).forEach(innerError => {
                                state.errorSchema = Object.assign(Object.assign({}, state.errorSchema), { [getPropName(field, innerError, isArray)]: Object.assign(Object.assign({}, (state.errorSchema[getPropName(field, innerError, isArray)] || {})), state.errorSchema[errorField][innerError]) });
                            });
                            state.errorSchema = (0, utils_1.immutableDelete)(state.errorSchema, errorField);
                        }
                    }
                });
            }
        });
        const { formDataTransformers = [] } = props.formContext;
        state.formContext = Object.assign(Object.assign({}, props.formContext), { formDataTransformers: [
                ...formDataTransformers,
                { "ui:field": "FlatField", props: origProps, targets: fields.map(field => `${props.idSchema.$id}_${field}`) }
            ] });
        state.registry = Object.assign(Object.assign({}, props.registry), { formContext: state.formContext });
        return state;
    }
};
FlatField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            "fields": PropTypes.arrayOf(PropTypes.string),
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object
};
FlatField = __decorate([
    VirtualSchemaField_1.default
], FlatField);
exports.default = FlatField;
