"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 BaseInputTemplate_1 = __importDefault(require("../templates/BaseInputTemplate"));
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const utils_1 = require("../../utils");
const react_spinner_1 = __importDefault(require("react-spinner"));
const ConfirmButton_1 = require("../components/ConfirmButton");
class InputWithDefaultValueButtonWidget extends React.Component {
    constructor(props) {
        super(props);
        this.onClick = () => {
            var _a;
            if (this.fetching || this.disabled) {
                return;
            }
            const { contextFieldForDefaultValue, apiQueryForDefaultValue, onClick } = (0, utils_1.getUiOptions)(this.props);
            if (contextFieldForDefaultValue) {
                const uiSchemaContext = this.props.formContext.uiSchemaContext || {};
                const defaultValue = uiSchemaContext[contextFieldForDefaultValue];
                this.changeValue(defaultValue);
            }
            else if (apiQueryForDefaultValue) {
                const { path, query = {}, resultKey, cache = false } = apiQueryForDefaultValue;
                const apiClient = this.props.formContext.apiClient;
                this.fetching = true;
                this.setState({ fetching: true });
                return apiClient.get(path, { query: Object.assign({ value: (_a = this.props.value) !== null && _a !== void 0 ? _a : "" }, query) }, cache).then(result => {
                    result = resultKey ? result === null || result === void 0 ? void 0 : result[resultKey] : result;
                    this.changeValue(result);
                }).catch(() => {
                }).finally(() => {
                    this.fetching = false;
                    this.setState({ fetching: false });
                });
            }
            if (onClick) {
                onClick();
            }
        };
        this.changeValue = (value) => {
            const { disableButtonAfterUse = false } = (0, utils_1.getUiOptions)(this.props);
            this.props.onChange(value);
            if (disableButtonAfterUse) {
                this.disabled = true;
                this.setState({ disabled: true });
            }
        };
        this.fetching = false;
        this.disabled = false;
        this.state = { fetching: false, disabled: false };
    }
    render() {
        const { InputGroup } = this.context.theme;
        const { buttonLabel, buttonVariant, confirmClick, confirmMessage } = (0, utils_1.getUiOptions)(this.props);
        const { disabled, readonly, id } = this.props;
        const { translations } = this.props.formContext;
        return (React.createElement(InputGroup, null,
            React.createElement(BaseInputTemplate_1.default, Object.assign({}, this.props)),
            React.createElement(InputGroup.Button, { className: "input-group-button" },
                React.createElement(ConfirmButton_1.ConfirmButton, { id: `${id}-default-value-button`, translations: translations, confirm: confirmClick, onClick: this.onClick, disabled: disabled || readonly || this.state.fetching || this.state.disabled, variant: buttonVariant, prompt: confirmMessage },
                    this.state.fetching && React.createElement(react_spinner_1.default, null),
                    buttonLabel))));
    }
}
InputWithDefaultValueButtonWidget.contextType = ReactContext_1.default;
InputWithDefaultValueButtonWidget.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            buttonLabel: PropTypes.string.isRequired,
            buttonVariant: PropTypes.string,
            contextFieldForDefaultValue: PropTypes.string,
            apiQueryForDefaultValue: PropTypes.shape({
                path: PropTypes.string.isRequired,
                query: PropTypes.object,
                resultKey: PropTypes.string,
                cache: PropTypes.bool
            }),
            disableButtonAfterUse: PropTypes.bool,
            confirmClick: PropTypes.bool,
            confirmMessage: PropTypes.string,
            onClick: PropTypes.func
        }).isRequired
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["string", "number", "integer"]),
    }).isRequired,
    value: PropTypes.string
};
exports.default = InputWithDefaultValueButtonWidget;
