"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 });
exports.computeUiSchema = exports.rulesPropType = exports.operationPropType = exports.rulePropType = void 0;
const React = __importStar(require("react"));
const PropTypes = __importStar(require("prop-types"));
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
const deepmerge_1 = __importDefault(require("deepmerge"));
const utils_1 = require("../../utils");
exports.rulePropType = PropTypes.oneOfType([
    PropTypes.shape({
        field: PropTypes.string.isRequired,
        regexp: PropTypes.string,
        valueIn: PropTypes.arrayOf(PropTypes.string),
        valueLengthLessThan: PropTypes.number,
        prop: PropTypes.string,
        complement: PropTypes.bool
    }),
    PropTypes.shape({
        rule: PropTypes.oneOf(["isAdmin", "isLoggedIn", "isEdit", "isReadonly"]),
        complement: PropTypes.bool
    }),
    PropTypes.oneOf(["isAdmin", "isLoggedIn", "isEdit", "isReadonly"]),
]);
exports.operationPropType = PropTypes.shape({
    type: PropTypes.oneOf(["merge", "wrap"]),
    uiSchema: PropTypes.object.isRequired,
});
exports.rulesPropType = PropTypes.oneOfType([
    exports.rulePropType,
    PropTypes.arrayOf(exports.rulePropType)
]);
const casePropType = PropTypes.shape({
    rules: exports.rulesPropType,
    operations: PropTypes.oneOfType([
        exports.operationPropType,
        PropTypes.arrayOf(exports.operationPropType)
    ])
});
/**
 * Transforms uiSchema according to conditional cases. Cases are not mutually exclusive.
 * uiSchema = {"ui:options": {
 *	cases: [
 *		rules: [
 *			{
 *				regexp: The regexp that the field must match.
 *				valueIn: An array that the field must be in.
 *				field: The field that the rule is being checked on (can be a JSON pointer or a field name)
 *			}
 *		],
 *		operations: [ // All the operations are performed if all rules pass.
 *			{
 *				type: "merge" or "wrap" "replace". "merge" deeply merges the conditional uiSchema to the nested uiSchema.
 *				                                   "wrap" sets the nested uiSchema inside conditional uiSchema.
 *				                                   "replace" (default) replaces nested uiSchema with conditional uiSchema.
 *				uiSchema: conditional uiSchema to use.
 *			}
 *		],
 *		else: [<same as operations>] // Operations performed if the rules do not pass.
 *		cache: <boolean> true by default. If you know the cases will cache, set this to false.
 *		       There will be a performance penalty on valueIn rule, as they are not indexed without caching.
 *	]
 * }
 * uiSchema: nested uiSchema
 * }
 */
let ConditionalUiSchemaField = class ConditionalUiSchemaField extends React.Component {
    constructor() {
        super(...arguments);
        this.cache = {};
    }
    static getName() { return "ConditionalUiSchemaField"; }
    getStateFromProps(props) {
        const { cases = [], cache = true, arrayMerge } = this.getUiOptions();
        const { uiSchema } = props;
        let computedUiSchema = uiSchema;
        (Array.isArray(cases) ? cases : [cases]).forEach(({ rules = [], operations = [], else: _else, arrayMerge: _arrayMerge }, idx) => {
            let passes;
            if (cache) {
                if (!this.cache[idx]) {
                    this.cache[idx] = {};
                }
                const check = (0, utils_1.checkRules)(rules, props, this.cache[idx]);
                const { cache } = check;
                passes = check.passes;
                this.cache = cache;
            }
            else {
                passes = (0, utils_1.checkRules)(rules, props);
            }
            if (passes) {
                computedUiSchema = (0, exports.computeUiSchema)(computedUiSchema, operations, _arrayMerge || arrayMerge);
            }
            else if (_else) {
                computedUiSchema = (0, exports.computeUiSchema)(computedUiSchema, _else, _arrayMerge || arrayMerge);
            }
        });
        return { uiSchema: computedUiSchema };
    }
};
ConditionalUiSchemaField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            cases: PropTypes.oneOfType([
                casePropType,
                PropTypes.arrayOf(casePropType)
            ]),
            cache: PropTypes.bool
        })
    }),
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array", "object", "string", "integer", "number", "boolean"])
    }).isRequired,
};
ConditionalUiSchemaField = __decorate([
    VirtualSchemaField_1.default
], ConditionalUiSchemaField);
exports.default = ConditionalUiSchemaField;
const computeUiSchema = (uiSchema, operations, arrayMerge = "replace") => {
    if (!operations)
        return uiSchema;
    return (Array.isArray(operations) ? operations : [operations]).reduce((_uiSchema, op) => {
        switch (op.type) {
            case "merge":
                uiSchema = (0, deepmerge_1.default)(uiSchema, op.uiSchema, { arrayMerge: arrayMerge === "replace"
                        ? (a1, a2) => a2
                        : (a1, a2) => [...a1, ...a2] });
                break;
            case "wrap":
                uiSchema = Object.assign(Object.assign({}, op.uiSchema), { uiSchema });
                break;
            case "jsonPointer":
                uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(uiSchema, op.value, op.pointer);
                break;
            case "replace":
            default:
                uiSchema = op.uiSchema;
        }
        return uiSchema;
    }, uiSchema);
};
exports.computeUiSchema = computeUiSchema;
