"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 utils_1 = require("../../utils");
const deepmerge_1 = __importDefault(require("deepmerge"));
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
/**
 * Transforms an object schema containing arrays to an array schema containing objects.
 *
 * uischema = {"ui:options": {
 *  uiSchema: <uiSchema> (uiSchema which is passed to array items)
 * }
 */
let ArrayCombinerField = class ArrayCombinerField extends React.Component {
    constructor() {
        super(...arguments);
        this.onChange = (formData) => {
            let origArraysContainer = {};
            if (!formData || formData.length === 0) {
                Object.keys(this.props.schema.properties).forEach((prop) => {
                    origArraysContainer[prop] = [];
                });
            }
            else {
                formData.forEach((obj) => {
                    Object.keys(this.props.schema.properties).forEach((arrName) => {
                        origArraysContainer[arrName] ?
                            origArraysContainer[arrName].push(obj[arrName]) :
                            (origArraysContainer[arrName] = [obj[arrName]]);
                    });
                });
            }
            this.props.onChange(origArraysContainer);
        };
    }
    static getName() { return "ArrayCombinerField"; }
    getStateFromProps(props) {
        const { additionalItemsAmount } = this.getUiOptions();
        let itemSchema = { type: "object", properties: {}, required: props.schema.required };
        let schema = { type: "array" };
        if (additionalItemsAmount)
            schema.additionalItems = itemSchema;
        if ("title" in props.schema)
            schema.title = props.schema.title;
        Object.keys(props.schema.properties).forEach((propertyName) => {
            let propertyOrigin = props.schema.properties[propertyName];
            let property = propertyOrigin.items;
            if (property.type === "object" || property.type === "array")
                throw "items properties can't be objects or arrays";
            if (propertyOrigin.title)
                property.title = propertyOrigin.title;
            itemSchema.properties[propertyName] = property;
        });
        schema.items = itemSchema;
        if (additionalItemsAmount) {
            schema.items = Array(additionalItemsAmount).fill(itemSchema);
            schema.additionalItems = itemSchema;
        }
        const uiSchema = Object.keys(props.schema.properties).reduce((_uiSchema, field) => {
            if (field in _uiSchema) {
                _uiSchema = Object.assign(Object.assign({}, _uiSchema), { items: Object.assign(Object.assign({}, (_uiSchema.items || {})), { [field]: _uiSchema[field] }) });
                (0, utils_1.immutableDelete)(_uiSchema, field);
            }
            return _uiSchema;
        }, props.uiSchema);
        function objectsToArray(array, objects) {
            if (objects)
                Object.keys(objects).forEach(dataCol => {
                    if (objects[dataCol])
                        for (var row in objects[dataCol]) {
                            let val = objects[dataCol][row];
                            if (!array[row])
                                array[row] = {};
                            array[row][dataCol] = val;
                        }
                });
            return array;
        }
        function rotateErrorSchema(rotatedErrorSchema, errorSchema) {
            if (errorSchema)
                Object.keys(errorSchema).forEach(property => {
                    const error = errorSchema[property];
                    if (property === "__errors") {
                        rotatedErrorSchema.__errors = error;
                    }
                    else {
                        if (error)
                            Object.keys(error).forEach(idx => {
                                if (idx === "__errors") {
                                    rotatedErrorSchema.__errors = rotatedErrorSchema.__errors ?
                                        [...rotatedErrorSchema.__errors, ...error.__errors] :
                                        error.__errors;
                                }
                                else {
                                    const propertyError = { [property]: error[idx] };
                                    rotatedErrorSchema[idx] = rotatedErrorSchema[idx] ?
                                        (0, deepmerge_1.default)(rotatedErrorSchema[idx], propertyError) : propertyError;
                                }
                            });
                    }
                });
            return rotatedErrorSchema;
        }
        let errorSchema = rotateErrorSchema({}, props.errorSchema);
        let formData = objectsToArray([], props.formData);
        formData.forEach((obj) => {
            Object.keys(itemSchema.properties).forEach((prop) => {
                if (!(prop in obj)) {
                    obj[prop] = (0, utils_1.getDefaultFormState)(itemSchema.properties[prop]);
                }
            });
        });
        return { schema, errorSchema, formData, uiSchema, onChange: this.onChange };
    }
};
ArrayCombinerField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            additionalItemsAmount: PropTypes.number
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object.isRequired
};
ArrayCombinerField = __decorate([
    VirtualSchemaField_1.default
], ArrayCombinerField);
exports.default = ArrayCombinerField;
