var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { GetBridFromChainException } from "./errors";
import { abortOnError, singleEndpoint, tryNextOnError, } from "./failoverStrategies";
import { FailoverStrategy } from "./enums";
export function getBrid(urlBase, chainId) {
    if (chainId >= 0) {
        const url = `${urlBase}/brid/iid_${chainId}`;
        return fetch(url).then((response) => {
            if (response.ok)
                return response.text();
            throw new GetBridFromChainException(chainId, response.statusText);
        });
    }
    else {
        const url = `${urlBase}/_debug`;
        return fetch(url).then((response) => {
            if (response.ok)
                return response
                    .json()
                    .then((json) => json.blockchain[json.blockchain.length - 1].brid);
            throw new GetBridFromChainException(chainId, response.statusText);
        });
    }
}
export function requestWithRetry(method, path, config, postObject) {
    return __awaiter(this, void 0, void 0, function* () {
        let response;
        switch (config.failoverStrategy) {
            case FailoverStrategy.AbortOnError:
                response = yield abortOnError({ method, path, config, postObject });
                break;
            case FailoverStrategy.TryNextOnError:
                response = yield tryNextOnError({ method, path, config, postObject });
                break;
            case FailoverStrategy.SingleEndpoint:
                response = yield singleEndpoint({ method, path, config, postObject });
                break;
        }
        return response;
    });
}
export function nextEndpoint(endpointPool) {
    return endpointPool[Math.floor(Math.random() * endpointPool.length)];
}
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export function convertToPrintable(responseObject) {
    if (typeof responseObject === "bigint") {
        return responseObject + "n";
    }
    else if (typeof responseObject === "object") {
        return JSON.stringify(responseObject, (key, value) => typeof value === "bigint" ? value + "n" : value);
    }
    else {
        return responseObject;
    }
}
//# sourceMappingURL=restclientutil.js.map