"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 PropTypes = __importStar(require("prop-types"));
const utils_1 = require("../../utils");
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const components_1 = require("../components");
const immutability_helper_1 = __importDefault(require("immutability-helper"));
const memoizee_1 = __importDefault(require("memoizee"));
const equals = require("deep-equal");
class MultiTagArrayField extends React.Component {
    constructor() {
        super(...arguments);
        this.state = { activeButtonIdx: undefined };
        this.affixContainerRef = React.createRef();
        this.onChange = (0, memoizee_1.default)((key) => (formData) => {
            const newFormData = Object.assign(Object.assign({}, this.props.formData), { [key]: formData });
            this.props.onChange(newFormData);
        });
        this.onButtonClick = (0, memoizee_1.default)((idx) => () => {
            const { activeButtonIdx } = this.state;
            if (activeButtonIdx === idx) {
                this.setState({ activeButtonIdx: undefined });
                return;
            }
            const { buttons = [] } = (0, utils_1.getUiOptions)(this.props.uiSchema);
            const options = buttons[idx];
            const { operation } = options;
            if (operation === "moveAll") {
                const { toField, fromField } = options;
                const toFieldNewValue = (this.props.formData[toField] || []).concat(this.props.formData[fromField] || []);
                const newFormData = Object.assign(Object.assign({}, this.props.formData), { [fromField]: [], [toField]: toFieldNewValue });
                this.props.onChange(newFormData);
            }
            else if (operation === "move" || operation === "delete") {
                this.setState({ activeButtonIdx: idx });
            }
        });
        this.onTagClick = (0, memoizee_1.default)((fromField) => (idx, e) => {
            const { activeButtonIdx } = this.state;
            if (activeButtonIdx === undefined) {
                return;
            }
            e.preventDefault();
            const { buttons = [] } = (0, utils_1.getUiOptions)(this.props.uiSchema);
            const options = buttons[activeButtonIdx];
            const { operation } = options;
            if (operation === "move" || operation === "delete") {
                let formData = this.props.formData;
                if (operation === "move") {
                    const { toField } = options;
                    if (fromField === toField) {
                        return;
                    }
                    const value = formData[fromField][idx];
                    formData = (0, immutability_helper_1.default)(formData, {
                        [fromField]: { $splice: [[idx, 1]] },
                        [toField]: { $apply: (values) => [...(values || []), value] }
                    });
                }
                else {
                    formData = (0, immutability_helper_1.default)(formData, { [fromField]: { $splice: [[idx, 1]] } });
                }
                this.props.onChange(formData);
            }
        });
    }
    componentDidUpdate(prevProps) {
        if (this.state.activeButtonIdx !== undefined) {
            const prevButtons = (0, utils_1.getUiOptions)(prevProps.uiSchema).buttons;
            const currentButtons = (0, utils_1.getUiOptions)(this.props.uiSchema).buttons;
            if (!equals(prevButtons, currentButtons)) {
                this.setState({ activeButtonIdx: undefined });
            }
        }
    }
    render() {
        const SchemaField = this.props.registry.fields.SchemaField;
        const { Row, Col } = this.context.theme;
        const { schema, uiSchema, idSchema, errorSchema, formData = {}, disabled, readonly } = this.props;
        const uiOptions = (0, utils_1.getUiOptions)(uiSchema);
        const { buttons = [] } = uiOptions;
        const { activeButtonIdx } = this.state;
        const propertyKeys = Object.keys(schema.properties);
        const containerClassNames = (0, utils_1.classNames)("laji-form-multi-tag-array-field", activeButtonIdx !== undefined && "laji-form-multi-tag-array-field-active", (disabled || readonly) && "laji-form-multi-tag-array-field-disabled");
        return (React.createElement(Row, { className: containerClassNames, ref: this.affixContainerRef },
            React.createElement(Col, { xs: 3, sm: 3, md: 2, lg: 2, className: "laji-form-multi-tag-array-field-buttons" },
                React.createElement(components_1.Affix, { containerRef: this.affixContainerRef, topOffset: this.props.formContext.topOffset + 15, bottomOffset: this.props.formContext.bottomOffset },
                    React.createElement("div", { className: "btn-group-vertical" }, buttons.map((btnProps, idx) => (React.createElement(components_1.Button, { key: idx, onClick: this.onButtonClick(idx), variant: btnProps.operation === "delete" ? "outline-danger" : "default", className: (0, utils_1.classNames)(btnProps.className, activeButtonIdx === idx ? "active" : ""), disabled: disabled || readonly }, btnProps.label)))))),
            React.createElement(Col, { xs: 9, sm: 9, md: 10, lg: 10, className: "laji-form-multi-tag-array-field-content" }, propertyKeys.map(key => {
                var _a, _b;
                return (React.createElement(SchemaField, Object.assign({}, this.props, { key: key, schema: Object.assign({ title: "" }, schema.properties[key]), uiSchema: Object.assign(Object.assign({ "ui:field": "TagArrayField" }, uiSchema[key]), { "ui:options": Object.assign(Object.assign(Object.assign({}, uiOptions), { buttons: undefined, onTagClick: this.onTagClick(key) }), (_a = uiSchema[key]) === null || _a === void 0 ? void 0 : _a["ui:options"]) }), errorSchema: errorSchema[key] || {}, idSchema: idSchema[key], formData: formData[key] || [], required: ((_b = uiSchema[key]) === null || _b === void 0 ? void 0 : _b["ui:required"]) || false, onChange: this.onChange(key), onBlur: this.props.onBlur, onFocus: this.props.onFocus, disabled: this.props.disabled, readonly: this.props.readonly, name: this.props.name })));
            }))));
    }
}
MultiTagArrayField.contextType = ReactContext_1.default;
MultiTagArrayField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            buttons: PropTypes.arrayOf(PropTypes.oneOfType([
                PropTypes.shape({
                    operation: PropTypes.oneOf(["moveAll"]),
                    fromField: PropTypes.string.isRequired,
                    toField: PropTypes.string.isRequired,
                    label: PropTypes.string,
                    className: PropTypes.string
                }),
                PropTypes.shape({
                    operation: PropTypes.oneOf(["move"]),
                    toField: PropTypes.string.isRequired,
                    label: PropTypes.string,
                    className: PropTypes.string
                }),
                PropTypes.shape({
                    operation: PropTypes.oneOf(["delete"]),
                    label: PropTypes.string,
                    className: PropTypes.string
                })
            ]))
        })
    }),
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object
};
exports.default = MultiTagArrayField;
