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 { Buffer } from "buffer";
import { logger } from "../..";
import { BlockchainUrlUndefinedException } from "../chromia/errors";
import { SerializedTransactionFormatException, UnvalidTxRidException, } from "../restclient/errors";
import { createRestClient, handlePostResponse } from "../restclient/restclient";
import * as gtxTool from "../gtx/gtx";
import { InvalidTransactionFormatException, MissingBlockchainError, MissingNodeUrlError, } from "./errors";
import { getBrid } from "../restclient/restclientutil";
import { toBuffer } from "../formatter";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Web3PromiEvent = require("web3-core-promievent");
export function getConfig(settings) {
    var _a, _b;
    return __awaiter(this, void 0, void 0, function* () {
        if (!settings.nodeURLPool && !settings.directoryNodeURLPool) {
            throw new MissingNodeUrlError();
        }
        if (!settings.blockchainRID &&
            typeof settings.blockchainIID === "undefined") {
            throw new MissingBlockchainError();
        }
        const nodeUrlPool = settings.directoryNodeURLPool
            ? yield getNodeUrls(settings)
            : typeof settings.nodeURLPool === "string"
                ? [settings.nodeURLPool]
                : Array.isArray(settings.nodeURLPool)
                    ? settings.nodeURLPool
                    : [];
        return {
            endpointPool: nodeUrlPool,
            blockchainRID: settings.blockchainRID
                ? settings.blockchainRID
                : yield getBrid(nodeUrlPool[0], settings.blockchainIID),
            pollingInterval: settings.pollingInterval || 500,
            attemptsPerEndpoint: ((_a = settings.failOverConfig) === null || _a === void 0 ? void 0 : _a.attemptsPerEndpoint) || 3,
            attemptInterval: ((_b = settings.failOverConfig) === null || _b === void 0 ? void 0 : _b.attemptInterval) || 500,
        };
    });
}
export function validTxRID(txRID) {
    if (txRID.length != 32) {
        const error = new UnvalidTxRidException(txRID);
        logger.error(error.toString());
        return false;
    }
    return true;
}
export function getNodeUrls(settings) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!settings.blockchainRID) {
            throw new MissingBlockchainError();
        }
        const nodeUrlPool = Array.isArray(settings.directoryNodeURLPool)
            ? settings.directoryNodeURLPool
            : typeof settings.directoryNodeURLPool === "string"
                ? [settings.directoryNodeURLPool]
                : [];
        const directoryBRID = yield getBrid(nodeUrlPool[0], 0);
        const queryObject = {
            type: "cm_get_blockchain_api_urls",
            blockchain_rid: settings.blockchainRID
                ? settings.blockchainRID
                : yield getBrid(nodeUrlPool[0], settings.blockchainIID),
        };
        const rest = createRestClient(nodeUrlPool, directoryBRID);
        const baseUrls = yield rest.query(queryObject);
        if (!baseUrls.length) {
            throw new BlockchainUrlUndefinedException(directoryBRID);
        }
        return baseUrls;
    });
}
export function convertToRellOperation(operations) {
    return operations.map((operation) => {
        var _a;
        return {
            opName: operation.name,
            args: (_a = operation.args) !== null && _a !== void 0 ? _a : [],
        };
    });
}
export function testPromiEvent() {
    const promiEvent = Web3PromiEvent();
    setTimeout(function () {
        promiEvent.eventEmitter.emit("sent", "Hello sent!");
        promiEvent.resolve("Hello resolve");
    }, 1000);
    return promiEvent.eventEmitter;
}
export function getSerializedGTX(gtx) {
    const gtxBytes = gtxTool.serialize(gtx);
    if (!Buffer.isBuffer(gtxBytes)) {
        throw new SerializedTransactionFormatException();
    }
    return gtxBytes;
}
export function getGTXFromBufferOrTransactionOrOperation(transaction, blockchainRID) {
    if (Buffer.isBuffer(transaction)) {
        return gtxTool.deserialize(transaction);
    }
    else if ("operations" in transaction) {
        return {
            blockchainRID: toBuffer(blockchainRID),
            operations: convertToRellOperation(transaction.operations),
            signers: transaction.signers,
            signatures: [],
        };
    }
    else if ("name" in transaction) {
        return {
            blockchainRID: toBuffer(blockchainRID),
            operations: convertToRellOperation([transaction]),
            signers: [],
            signatures: [],
        };
    }
    else {
        throw new InvalidTransactionFormatException();
    }
}
export const callbackPromiseBuilder = (reject, resolve, callback) => {
    return (error, result) => {
        if (error) {
            if (typeof callback === "function") {
                callback(error, null);
            }
            reject(error);
        }
        else {
            if (typeof callback === "function") {
                callback(null, result);
            }
            resolve(result);
        }
    };
};
export const handlePostResponsePromisified = (error, statusCode, rspBody) => {
    return new Promise((resolve, reject) => {
        handlePostResponse(error, statusCode, rspBody, (_error) => {
            if (_error) {
                reject(_error);
            }
            else {
                resolve();
            }
        });
    });
};
//# sourceMappingURL=utils.js.map