"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 Context_1 = __importDefault(require("../../Context"));
const components_1 = require("../components");
const utils_1 = require("../../utils");
class _FieldTemplate extends React.Component {
    constructor(props) {
        super(props);
        this.canFocus = () => {
            const { formContext } = this.props;
            const { uiSchema = {} } = (formContext.formRef.current || { props: {} }).props;
            return uiSchema.autoFocus !== false;
        };
        this.receiveId = (id) => {
            this.setState({ id }, () => {
                const { idToFocus, idToScroll } = (0, Context_1.default)(this.props.formContext.contextId);
                if (this.canFocus() && idToFocus === id) {
                    this.props.formContext.utils.focusAndScroll(idToFocus, idToScroll);
                }
            });
        };
        if ((0, utils_1.getUiOptions)(props.uiSchema).reserveId === false) {
            this.state = {};
            return;
        }
        const id = this.props.formContext.services.DOMIds.reserve(this.props.id, this.receiveId);
        if (id) {
            this.state = { id };
        }
        else {
            this.state = {};
        }
    }
    componentDidMount() {
        const { formContext } = this.props;
        const contextId = formContext.contextId;
        const _context = (0, Context_1.default)(contextId);
        const { idToFocus, idToScroll } = _context;
        if (this.canFocus() && idToFocus !== undefined && this.state.id === idToFocus) {
            if (this.props.formContext.utils.focusAndScroll(idToFocus, idToScroll)) {
                _context.idToFocus = undefined;
                _context.idToScroll = undefined;
            }
        }
    }
    UNSAFE_componentWillReceiveProps(props) {
        if ((0, utils_1.getUiOptions)(props.uiSchema).reserveId !== false && this.props.id !== props.id) {
            this.props.formContext.services.DOMIds.release(this.props.id, this.receiveId);
            const id = props.formContext.services.DOMIds.reserve(props.id, this.receiveId);
            id && this.receiveId(id);
        }
    }
    componentWillUnmount() {
        if ((0, utils_1.getUiOptions)(this.props.uiSchema).reserveId === false) {
            return;
        }
        this.props.formContext.services.DOMIds.release(this.props.id, this.receiveId);
    }
    render() {
        const { id, classNames: _classNames, children, rawErrors, description, hidden, required, displayLabel, schema, uiSchema, label: _label, forceDisplayLabel } = this.props;
        const label = "ui:title" in uiSchema
            ? uiSchema["ui:title"]
            : "title" in schema
                ? schema.title
                : _label;
        if (hidden || uiSchema["ui:field"] === "HiddenField" || uiSchema["ui:widget"] === "HiddenWidget") {
            return children;
        }
        const inlineHelp = uiSchema["ui:inlineHelp"];
        const belowHelp = uiSchema["ui:belowHelp"];
        const htmlId = this.state.id ? `_laji-form_${this.state.id}` : undefined;
        const _displayLabel = forceDisplayLabel ||
            ((schema.items && schema.items.enum && !(0, utils_1.isMultiSelect)(schema, uiSchema)) ? false : displayLabel);
        let warnings = [];
        const errors = (rawErrors || []).reduce((arr, err) => {
            if (err.includes("[warning]")) {
                warnings.push((0, utils_1.formatErrorMessage)(err));
            }
            else {
                arr.push((0, utils_1.formatErrorMessage)(err));
            }
            return arr;
        }, []);
        const warningClassName = (warnings.length > 0 && errors.length === 0) && "laji-form-warning-container";
        const { Label, errorsAsPopup } = this.props.formContext;
        const component = (errorsComponent) => (React.createElement("div", { className: (0, utils_1.classNames)(_classNames, warningClassName), id: htmlId },
            label && _displayLabel ? React.createElement(Label, { label: label, uiSchema: uiSchema, id: id, required: required || uiSchema["ui:required"], registry: this.props.registry }) : null,
            _displayLabel && description ? description : null,
            React.createElement("div", null,
                inlineHelp ? React.createElement("div", { className: "pull-left" }, children) : children,
                inlineHelp
                    ? (React.createElement("div", { className: "pull-left" },
                        React.createElement(components_1.Help, { help: inlineHelp, id: `${htmlId}-inline-help`, focusable: true, standalone: true }))) : null),
            belowHelp ?
                React.createElement("div", { className: "small text-muted", dangerouslySetInnerHTML: { __html: belowHelp } }) :
                null,
            errorsComponent));
        const errorsComponent = (React.createElement(React.Fragment, null,
            errors.length > 0 ?
                React.createElement("ul", { id: `laji-form-error-container-${id}`, className: "laji-form-error-container" }, errors.map((error, i) => (React.createElement("li", { key: i }, error))))
                : null,
            warnings.length > 0 ?
                React.createElement("ul", { id: `laji-form-warning-container-${id}`, className: "laji-form-warning-container" }, warnings.map((warning, i) => (React.createElement("li", { key: i }, warning))))
                : null));
        if (errorsAsPopup && (rawErrors || []).length) {
            return React.createElement(components_1.TooltipComponent, { placement: "bottom", tooltip: errorsComponent, className: "location-chooser-errors" }, component());
        }
        return component(errorsComponent);
    }
}
exports.default = _FieldTemplate;
