"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const post_1 = __importDefault(require("lib/api/post"));
const mounted_1 = __importDefault(require("./mounted"));
const awaiting_1 = require("awaiting");
function useAPI(endpoint, params, cache_s) {
    const [error, setError] = (0, react_1.useState)("");
    const [result, setResult] = (0, react_1.useState)(undefined);
    const [calling, setCalling] = (0, react_1.useState)(false);
    const queue = (0, react_1.useRef)([]);
    const isMounted = (0, mounted_1.default)();
    async function call(endpoint1 = endpoint, params1 = params, cache_s1 = cache_s) {
        if (endpoint1 == undefined)
            return;
        if (calling) {
            queue.current.push({
                endpoint: endpoint1,
                params: params1,
                cache_s: cache_s1,
            });
            return;
        }
        setCalling(true);
        let result;
        try {
            result = await (0, post_1.default)(endpoint1, params1, cache_s);
        }
        catch (err) {
            if (!isMounted.current)
                return;
            setCalling(false);
            setError(`${err}`);
            setResult({ error: err });
            queue.current = [];
            return;
        }
        if (!isMounted.current)
            return;
        setCalling(false);
        setResult(result);
        if (queue.current.length > 0) {
            const next = queue.current.shift();
            if (next == null)
                return;
            const { endpoint, params, cache_s } = next;
            if (!isMounted.current)
                return;
            await (0, awaiting_1.delay)(1);
            call(endpoint, params, cache_s);
        }
    }
    (0, react_1.useEffect)(() => {
        if (endpoint) {
            call(endpoint, params, cache_s);
        }
    }, [endpoint + JSON.stringify(params)]);
    return { error, result, calling, call };
}
exports.default = useAPI;
//# sourceMappingURL=api.js.map