"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 utils_1 = require("@rjsf/utils");
const utils_2 = require("../../utils");
const ArrayFieldTemplate_1 = require("../templates/ArrayFieldTemplate");
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const core_1 = require("@rjsf/core");
const ObjectFieldTemplate_1 = require("../templates/ObjectFieldTemplate");
exports.default = (props) => {
    const id = (0, utils_2.getUUID)(props.formData);
    const formContext = id
        ? Object.assign(Object.assign({}, props.formContext), { _parentLajiFormId: id }) : props.formContext;
    const uiSchema = props.uiSchema["ui:grid"] && !props.uiSchema["ui:ObjectFieldTemplate"]
        ? Object.assign(Object.assign({}, props.uiSchema), { "ui:ObjectFieldTemplate": GridTemplate }) : props.uiSchema;
    const { ObjectField } = (0, core_1.getDefaultRegistry)().fields;
    return React.createElement(ObjectField, Object.assign({}, props, { uiSchema: uiSchema, registry: Object.assign(Object.assign({}, props.registry), { formContext }), formContext: formContext }));
};
function GridTemplate(props) {
    const { schema, uiSchema, idSchema, properties } = props;
    const TitleFieldTemplate = (0, utils_1.getTemplate)("TitleFieldTemplate", props.registry, (0, utils_2.getUiOptions)(props.uiSchema));
    const gridOptions = props.uiSchema["ui:grid"] || {};
    const { ButtonToolbar, Row, Col } = React.useContext(ReactContext_1.default).theme;
    const rows = [];
    const lastRow = [];
    const colsToRows = {};
    (gridOptions.rows || []).forEach((row, i) => {
        row.forEach(col => {
            colsToRows[col] = i;
        });
    });
    const { rowTitles = [], classNames = {} } = gridOptions;
    const { Label } = props.formContext;
    const addRowTitles = (rows, rowTitles) => {
        for (let i = 0; i < rowTitles.length; i++) {
            rows[i] = [];
            const titleCols = getCols(props, { type: "string" }, uiSchema["rowTitle"], "rowTitle");
            rows[i].push(React.createElement(Col, Object.assign({}, titleCols, { key: "title_" + i, className: classNames["rowTitle"] }),
                React.createElement(Label, { id: idSchema.$id + "_row_" + i, label: rowTitles[i].title, uiSchema: { "ui:help": rowTitles[i].help } })));
        }
    };
    function getRow(col, colsToRows, rows) {
        const colRow = colsToRows[col];
        if (colRow !== undefined) {
            if (!rows[colRow])
                rows[colRow] = [];
            return rows[colRow];
        }
        else {
            return lastRow;
        }
    }
    addRowTitles(rows, rowTitles);
    (0, utils_1.orderProperties)(Object.keys(schema.properties), uiSchema["ui:order"]).forEach(propertyName => {
        const property = schema.properties[propertyName];
        if (!property)
            return;
        const uiSchemaProperty = uiSchema[propertyName];
        const cols = getCols(props, property, uiSchemaProperty, propertyName);
        const propertiesByName = properties.reduce((propertiesByName, _prop) => {
            propertiesByName[_prop.name] = _prop;
            return propertiesByName;
        }, {});
        if (!(0, utils_2.isHidden)(uiSchema, propertyName))
            getRow(propertyName, colsToRows, rows).push(React.createElement(Col, Object.assign({}, cols, { className: classNames[propertyName], key: propertyName }), propertiesByName[propertyName].content));
    });
    if (lastRow.length > 0)
        rows.push(lastRow);
    const { title } = schema;
    const { "ui:title": _title } = uiSchema;
    let fieldTitle = _title || (title !== undefined ? title : props.name);
    let buttons = (0, ObjectFieldTemplate_1.getGlyphButtons)(props);
    const [topButtons, bottomButtons, leftButtons, rightButtons] = ["top", "bottom", "left", "right"].map(pos => {
        const buttons = (0, ArrayFieldTemplate_1.getButtonsForPosition)(props, (0, utils_2.getUiOptions)(uiSchema).buttons, pos, "no default");
        return buttons
            ? (React.createElement(ButtonToolbar, { key: `buttons-${pos}` }, (0, ArrayFieldTemplate_1.getButtonsForPosition)(props, (0, utils_2.getUiOptions)(uiSchema).buttons, pos, "no default"))) : null;
    });
    const { containerClassName, schemaClassName, buttonsClassName } = (0, ObjectFieldTemplate_1.getObjectTemplateClassNames)(props, buttons);
    buttons = React.createElement("div", { className: buttonsClassName }, buttons);
    const titleUiSchema = Object.assign(Object.assign({}, uiSchema), { "ui:renderedButtons": buttons });
    return (React.createElement("div", { className: containerClassName },
        React.createElement("fieldset", { className: schemaClassName },
            !(0, utils_2.isEmptyString)(fieldTitle) ?
                React.createElement(TitleFieldTemplate, { title: fieldTitle, schema: schema, uiSchema: titleUiSchema, registry: props.registry, id: idSchema.$id }) : null,
            topButtons,
            leftButtons && React.createElement("div", { className: "pull-left" }, leftButtons),
            rows.map((row, i) => React.createElement(Row, { key: i }, row)),
            rightButtons && React.createElement("div", { className: "pull-right" }, rightButtons),
            bottomButtons),
        !props.title && buttons ? buttons : null));
}
function getCols(props, schema, uiSchema, property) {
    const options = props.uiSchema["ui:grid"];
    const cols = { lg: 12, md: 12, sm: 12, xs: 12 };
    const uiField = uiSchema && uiSchema["ui:field"] ? uiSchema["ui:field"] : undefined;
    Object.keys(cols).forEach(col => {
        const optionCol = options[col];
        if ((!(0, utils_2.isObject)(optionCol) || !optionCol[property])
            && schema.type === "array"
            && !(schema.items && schema.items.enum && (0, utils_2.isMultiSelect)(schema, uiSchema)
                || uiField === "SingleItemArrayField"
                || (schema.items && schema.items.type === "string" && uiField !== "ImageArrayField" && uiField !== "AudioArrayField"))
            || (schema.type === "string" && uiSchema && (0, utils_2.getNestedUiFieldsList)(uiSchema).includes("SelectTreeField"))) {
            return cols;
        }
        if ((0, utils_2.isObject)(optionCol)) {
            let selector = undefined;
            if (optionCol[property])
                selector = property;
            else if (optionCol["*"])
                selector = "*";
            cols[col] = parseInt(optionCol[selector]);
        }
        else {
            cols[col] = parseInt(optionCol);
        }
    });
    return cols;
}
