"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 VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
window.PropTypes = PropTypes;
const conditionPropType = {
    regexp: PropTypes.string,
    length: PropTypes.number,
    reverse: PropTypes.bool,
};
const rulePropType = PropTypes.shape({
    transformations: PropTypes.object.isRequired,
    conditions: (props, propName, componentName) => Object.keys(props[propName]).every(prop => PropTypes.checkPropTypes(conditionPropType, props[propName][prop], propName, componentName))
}).isRequired;
/**
 * Changes formData on onChange event according to conditional rules.
 * uiSchema = {
 *   "ui:options": {
 *     rules: { // Can also be an array of rules
 *       transformations: {
 *        <field name to change if conditions met>: <new value>
 *       },
 *       conditions: {
 *         <conditional field name>: { // Note that regexp and length must both pass for this rule to pass.
 *           regexp: <string> <if the conditional field value matches this regexp, this condition will pass>
 *           length: <number> <if the conditional field value length is equal or more, this conndition will pass>
 *           reverse: <boolean> <Reverses the passing value>
 *         }
 *       }
 *     }
 *   }
 * }
 */
let ConditionalOnChangeField = class ConditionalOnChangeField extends React.Component {
    constructor() {
        super(...arguments);
        this.onChange = (formData) => {
            const { rules } = this.getUiOptions();
            (Array.isArray(rules) ? rules : [rules]).forEach(({ conditions, transformations }) => {
                let passes = true;
                // If transforming field is updated, do nothing
                // (If a transforming field is also a condition field, the field would take the conditional value always when updated).
                if (Object.keys(transformations).some(field => formData && formData[field] && formData[field] !== this.props.formData[field])) {
                    return;
                }
                // If condition fields didn't change, do nothing.
                if (Object.keys(conditions).every(field => formData && formData[field] && formData[field] === this.props.formData[field])) {
                    return;
                }
                for (let field in conditions) {
                    const condition = conditions[field];
                    const { regexp, length, reverse } = condition;
                    if (passes && regexp !== undefined) {
                        const regexp = new RegExp(condition.regexp.replace("%default", this.props.schema.properties[field].default));
                        const result = `${formData[field]}`.match(regexp);
                        passes = reverse ? !result : result;
                    }
                    if (passes && length !== undefined) {
                        const result = (formData[field] || []).length >= length;
                        passes = reverse ? !result : result;
                    }
                    if (!passes)
                        break;
                }
                if (passes) {
                    let formDataChange = {};
                    if (transformations)
                        for (let transformField in transformations) {
                            formDataChange[transformField] = transformations[transformField];
                        }
                    formData = Object.assign(Object.assign({}, formData), formDataChange);
                }
            });
            this.props.onChange(formData);
        };
    }
    static getName() { return "ConditionalOnChangeField"; }
    getStateFromProps() {
        return { onChange: this.onChange };
    }
};
ConditionalOnChangeField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            rules: PropTypes.oneOfType([
                rulePropType,
                PropTypes.arrayOf(rulePropType)
            ]).isRequired
        }).isRequired,
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object.isRequired
};
ConditionalOnChangeField = __decorate([
    VirtualSchemaField_1.default
], ConditionalOnChangeField);
exports.default = ConditionalOnChangeField;
