"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 utils_1 = require("../../utils");
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
const components_1 = require("../components");
const deepmerge_1 = __importDefault(require("deepmerge"));
const ReactContext_1 = __importDefault(require("../../ReactContext"));
let UnitCountShorthandField = class UnitCountShorthandField extends React.Component {
    constructor(props) {
        super(props);
        this.parseCode = this.parseCode.bind(this);
    }
    static getName() { return "UnitCountShorthandField"; }
    getStateFromProps(props) {
        const { uiSchema, formData } = props;
        const { shorthandField, taxonIDField } = (0, utils_1.getUiOptions)(props.uiSchema);
        const shortHandUiSchema = (0, deepmerge_1.default)((0, utils_1.parseJSONPointer)(props.uiSchema, shorthandField) || {}, {
            "ui:widget": CodeReader,
            "ui:options": {
                parseCode: this.parseCode,
                taxonID: (0, utils_1.parseJSONPointer)(formData, taxonIDField)
            }
        });
        const _uiSchema = (0, utils_1.updateSafelyWithJSONPointer)(uiSchema, shortHandUiSchema, shorthandField);
        return Object.assign(Object.assign({}, props), { uiSchema: _uiSchema });
    }
    parseCode(value, taxonId) {
        const { apiClient } = this.props.formContext;
        let formData = this.props.formData;
        const { shorthandField, pairCountField } = (0, utils_1.getUiOptions)(this.props.uiSchema);
        let timestamp = Date.now();
        this.promiseTimestamp = timestamp;
        return new Promise((resolve, reject) => {
            if (!value || !taxonId) {
                formData = (0, utils_1.updateSafelyWithJSONPointer)(formData, undefined, pairCountField);
                this.props.onChange(formData);
                resolve({ success: undefined });
                return;
            }
            apiClient.get("/shorthand/unit/water-bird-pair-count", { query: { query: value, taxonID: taxonId } }).then(suggestion => {
                if (timestamp !== this.promiseTimestamp) {
                    reject();
                    return;
                }
                formData = (0, utils_1.updateSafelyWithJSONPointer)(formData, suggestion.key, shorthandField);
                formData = (0, utils_1.updateSafelyWithJSONPointer)(formData, suggestion.value, pairCountField);
                this.props.onChange(formData);
                resolve({ success: suggestion.key ? true : undefined, value: suggestion.key });
            }).catch(() => {
                if (timestamp !== this.promiseTimestamp) {
                    reject();
                    return;
                }
                formData = (0, utils_1.updateSafelyWithJSONPointer)(formData, undefined, pairCountField);
                this.props.onChange(formData);
                resolve({ success: false, value: value });
            });
        });
    }
};
UnitCountShorthandField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            shorthandField: PropTypes.string.isRequired,
            pairCountField: PropTypes.string.isRequired,
            taxonIDField: PropTypes.string.isRequired
        }).isRequired
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object.isRequired
};
UnitCountShorthandField = __decorate([
    VirtualSchemaField_1.default
], UnitCountShorthandField);
exports.default = UnitCountShorthandField;
class CodeReader extends React.Component {
    constructor(props) {
        super(props);
        this.onChange = ({ target: { value } }) => {
            this.props.onChange(value);
        };
        this.onKeyDown = (e) => {
            if (e.key === "Enter") {
                this.onBlur();
            }
        };
        this.state = { loading: false };
        this.onBlur = this.onBlur.bind(this);
    }
    componentDidUpdate(prevProps) {
        if (prevProps.options.taxonID !== this.props.options.taxonID) {
            this.onBlur();
        }
    }
    render() {
        let validationState = null;
        if (this.state.success === false) {
            validationState = "error";
        }
        else if (this.state.success) {
            validationState = "success";
        }
        const { formContext } = this.props;
        const { translations } = formContext;
        const inputElem = (React.createElement(components_1.FetcherInput, { id: this.props.id, loading: this.state.loading, value: this.props.value || "", validationState: validationState, onBlur: this.onBlur, onKeyDown: this.onKeyDown, onChange: this.onChange }));
        const { FormGroup, HelpBlock } = this.context.theme;
        return (React.createElement(FormGroup, { validationState: this.state.success === false ? "error" : undefined },
            inputElem,
            this.state.success === false ? (React.createElement(HelpBlock, null, translations.InvalidUnitCode)) : null,
            React.createElement("div", { className: "small text-muted", dangerouslySetInnerHTML: { __html: this.props.help } })));
    }
    onBlur() {
        const { value, options } = this.props;
        const { parseCode, taxonID } = options;
        if (!(value === this.state.value && taxonID === this.state.taxonID)) {
            this.setState({ value, taxonID, loading: true, success: undefined });
            this.props.formContext.services.submitHooks.add(this.props, () => {
                return parseCode(value, taxonID).then((result) => {
                    this.setState({ loading: false, success: result.success, value: result.value });
                });
            });
        }
    }
}
CodeReader.contextType = ReactContext_1.default;
CodeReader.propTypes = {
    options: PropTypes.shape({
        parseCode: PropTypes.func.isRequired,
        taxonID: PropTypes.string
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["string"])
    }),
    value: PropTypes.string
};
