"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 Context_1 = __importDefault(require("../../Context"));
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const components_1 = require("../components");
const AutosuggestWidget_1 = require("../widgets/AutosuggestWidget");
const ArrayFieldTemplate_1 = require("../templates/ArrayFieldTemplate");
class UnitShorthandField extends React.Component {
    constructor(props) {
        super(props);
        this.getStateFromProps = (props) => {
            const { persistenceKey } = (0, utils_1.getUiOptions)(props.uiSchema);
            let showSchema = undefined;
            if (persistenceKey) {
                const persistingContainer = (0, Context_1.default)(`${props.formContext.contextId}_UNIT_SHORTHAND_FIELD_PERSISTENCE_${persistenceKey}`);
                if (persistingContainer && "value" in persistingContainer) {
                    showSchema = persistingContainer.value;
                }
                else {
                    showSchema = this.shouldShowSchema(props);
                }
            }
            else {
                showSchema = this.shouldShowSchema(props);
            }
            return { showSchema };
        };
        this.UNSAFE_componentWillReceiveProps = (props) => {
            this.setState(this.getStateFromProps(props));
        };
        this.shouldShowSchema = (props) => {
            let { showSchema } = this.state;
            if (this.state.showSchema === undefined && !this.props.formContext.utils.formDataIsEmpty(props)) {
                showSchema = true;
            }
            return showSchema;
        };
        this.onToggleButtonClick = () => () => {
            const { persistenceKey } = (0, utils_1.getUiOptions)(this.props.uiSchema);
            this.setState({ showSchema: !this.state.showSchema }, () => {
                this.props.formContext.utils.focusById(this.props.idSchema.$id);
                (0, Context_1.default)(`${this.props.formContext.contextId}_UNIT_SHORTHAND_FIELD_PERSISTENCE_${persistenceKey}`).value = this.state.showSchema;
            });
        };
        this.getToggleButton = () => {
            return {
                glyph: "resize-small",
                fn: this.onToggleButtonClick,
                tooltip: this.props.formContext.translations[this.state.showSchema ? "OpenShorthand" : "CloseShorthand"],
                tooltipPlacement: "left",
                active: !this.state.showSchema
            };
        };
        this.onCodeChange = (formData = {}) => {
            const { autocopy, autofocus } = (0, utils_1.getUiOptions)(this.props.uiSchema);
            if (!autofocus)
                this.props.formContext.globals.idToFocus = this.props.idSchema.$id;
            this.onNextTick = () => {
                if (autocopy) {
                    this.props.formContext.services.customEvents.send(this.props.idSchema.$id, "copy");
                }
                else if (autofocus) {
                    this.props.formContext.services.customEvents.send(this.props.idSchema.$id, "focus", "last");
                }
                this.setState({ showSchema: true });
            };
            this.props.onChange((0, utils_1.getDefaultFormState)(this.props.schema, Object.assign(Object.assign({}, this.props.formData), formData)));
        };
        this.state = { showSchema: (0, utils_1.getUiOptions)(props.uiSchema).showSchema };
        this.state = Object.assign(Object.assign({}, this.state), this.getStateFromProps(props));
    }
    componentDidUpdate() {
        if (this.onNextTick) {
            this.onNextTick();
            this.onNextTick = undefined;
        }
    }
    render() {
        const { uiSchema, formContext, disabled, readonly } = this.props;
        const { SchemaField } = this.props.registry.fields;
        const { shorthandField, lineTransect } = (0, utils_1.getUiOptions)(this.props.uiSchema);
        const toggleButton = this.getToggleButton();
        const tailUiSchema = (0, utils_1.getNestedTailUiSchema)(uiSchema);
        let help = tailUiSchema && tailUiSchema[shorthandField] && tailUiSchema[shorthandField]["ui:belowHelp"];
        const uiSchemaWithoutHelp = (0, utils_1.isEmptyString)(help) ? uiSchema : (0, utils_1.updateTailUiSchema)(uiSchema, { [shorthandField]: { "ui:belowHelp": { $set: undefined } } });
        const id = (shorthandField && this.props.idSchema[shorthandField]) ?
            this.props.idSchema[shorthandField].$id :
            `${this.props.idSchema.$id}_shortHandField`;
        let innerUiSchema = undefined;
        if (this.state.showSchema) {
            innerUiSchema = (0, utils_1.getInnerUiSchema)(Object.assign({}, uiSchemaWithoutHelp));
            const innerOptions = (0, utils_1.getUiOptions)(innerUiSchema);
            innerUiSchema = Object.assign(Object.assign({}, innerUiSchema), { "ui:options": Object.assign(Object.assign({}, innerOptions), { buttons: [...(innerOptions.buttons || []), toggleButton] }) });
        }
        return !this.state.showSchema ? (React.createElement("div", { className: "laji-form-field-template-item", id: `_laji-form_${id}` },
            React.createElement(CodeReader, { translations: this.props.formContext.translations, onChange: this.onCodeChange, value: this.props.formData[shorthandField], formID: (0, utils_1.getUiOptions)(this.props.uiSchema).formID || formContext.formID || formContext.uiSchemaContext.formID, help: help, id: id, formContext: formContext, disabled: disabled, readonly: readonly, lineTransect: lineTransect, className: "laji-form-field-template-schema" }),
            React.createElement("div", { className: "laji-form-field-template-buttons" }, (0, ArrayFieldTemplate_1.getButton)(toggleButton)))) : (React.createElement(SchemaField, Object.assign({}, this.props, { uiSchema: innerUiSchema })));
    }
}
UnitShorthandField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            shorthandField: PropTypes.string,
            formID: PropTypes.string,
            showSchema: PropTypes.bool,
            persistenceKey: PropTypes.string
        }).isRequired,
        uiSchema: PropTypes.object
    }),
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object.isRequired
};
exports.default = UnitShorthandField;
class CodeReader extends React.Component {
    constructor(props) {
        super(props);
        this.UNSAFE_componentWillReceiveProps = (props) => {
            this.setState(this.getStateFromProps(props));
        };
        this.getStateFromProps = (props) => {
            let state = this.state;
            if (this.state.value === "" && !(0, utils_1.isEmptyString)(props.value)) {
                state.value = props.value;
            }
            return state;
        };
        this.onKeyDown = (e) => {
            if (e.key === "Enter") {
                this.getCode();
            }
        };
        this.onFetcherInputChange = ({ target: { value } }) => {
            if (this.mounted)
                this.setState({ value });
        };
        this.onAutosuggestChange = (formData) => {
            this.props.onChange(formData);
        };
        this.onSuggestionSelected = ({ unit }) => {
            const { formContext } = this.props;
            unit = (0, utils_1.bringRemoteFormData)(unit, formContext);
            this.props.onChange(unit);
        };
        this.renderSuggestion = (suggestion) => {
            const { translations } = this.props;
            return suggestion.isNonMatching
                ? React.createElement("span", { className: "text-muted" },
                    suggestion.value,
                    " ",
                    React.createElement("i", null,
                        "(",
                        translations.unknownSpeciesName,
                        ")"))
                : suggestion.value;
        };
        this.getCode = () => {
            const { value } = this.state;
            if (!(0, utils_1.isEmptyString)(this.props.value) && (0, utils_1.isEmptyString)(value) && (!this.value || this.value.length < 3)) {
                this.mounted && this.setState({ loading: true });
                this.mounted && this.setState({ failed: false, loading: false }, () => {
                    (0, utils_1.isEmptyString)(this.value) && this.props.onChange(undefined);
                });
            }
            else if (value.length >= 3) {
                this.mounted && this.setState({ loading: true });
                this.apiClient.get("/shorthand/unit/line-transect", { query: { query: value } }).then(response => {
                    this.props.onChange(response.unit);
                }).catch(() => {
                    this.mounted && this.setState({ failed: true, loading: false });
                });
            }
        };
        this.state = { value: "" };
        this.state = this.getStateFromProps(props);
        this.apiClient = props.formContext.apiClient;
    }
    componentDidMount() {
        this.mounted = true;
    }
    componentWillUnmount() {
        this.mounted = false;
    }
    render() {
        const { translations, readonly, disabled, lineTransect } = this.props;
        let validationState = null;
        if (this.state.failed === true)
            validationState = "warning";
        else if (!(0, utils_1.isEmptyString)(this.props.value) && this.props.value === this.state.value)
            validationState = "success";
        const { formContext } = this.props;
        const inputElem = lineTransect ? (React.createElement(components_1.FetcherInput, { id: this.props.id, loading: this.state.loading, value: this.state.value, validationState: validationState, onChange: this.onFetcherInputChange, onBlur: this.getCode, onKeyDown: this.onKeyDown, readonly: readonly, disabled: disabled })) : (React.createElement("div", { className: "unit-shorthand" },
            React.createElement(AutosuggestWidget_1.Autosuggest, { autosuggestField: "unit", onSuggestionSelected: this.onSuggestionSelected, renderSuggestion: this.renderSuggestion, onChange: this.onAutosuggestChange, formContext: formContext, allowNonsuggestedValue: false })));
        const { FormGroup, HelpBlock } = this.context.theme;
        return (React.createElement(FormGroup, { validationState: this.state.failed ? "error" : undefined },
            inputElem,
            this.state.failed
                ? (React.createElement(HelpBlock, null, translations.InvalidUnitCode)) : null,
            React.createElement("div", { className: "small text-muted", dangerouslySetInnerHTML: { __html: this.props.help } })));
    }
}
CodeReader.contextType = ReactContext_1.default;
