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 { SerializedTransactionFormatException, UnvalidTxRidException, } from "../restclient/errors";
import { createRestClient, handlePostResponse } from "../restclient/restclient";
import * as gtxTool from "../gtx/gtx";
import { BlockchainUrlUndefinedException, DirectoryNodeUrlPoolExeption, InvalidTransactionFormatException, MissingBlockchainError, MissingNodeUrlError, } from "./errors";
import { getBrid } from "../restclient/restclientutil";
import { toBuffer } from "../formatter";
import { FailoverStrategy } from "../restclient/enums";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Web3PromiEvent = require("web3-core-promievent");
export function getConfig(settings) {
    var _a, _b, _c;
    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 getNodeUrlsForBlockchainFromDirectoryChain(ensureArray(settings.directoryNodeUrlPool), settings.blockchainRid, settings.blockchainIid)
            : 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,
            failoverStrategy: ((_a = settings.failOverConfig) === null || _a === void 0 ? void 0 : _a.strategy) || FailoverStrategy.AbortOnError,
            attemptsPerEndpoint: ((_b = settings.failOverConfig) === null || _b === void 0 ? void 0 : _b.attemptsPerEndpoint) || 3,
            attemptInterval: ((_c = settings.failOverConfig) === null || _c === void 0 ? void 0 : _c.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 getNodeUrlsForBlockchainFromDirectoryChain(directoryNodeURLPool, blockchainRid, blockchainIid) {
    return __awaiter(this, void 0, void 0, function* () {
        if (directoryNodeURLPool.length === 0) {
            throw new DirectoryNodeUrlPoolExeption();
        }
        if (!(blockchainRid || blockchainIid != undefined)) {
            throw new MissingBlockchainError();
        }
        const directoryBRID = yield getBrid(directoryNodeURLPool[0], 0);
        const queryObject = {
            type: "cm_get_blockchain_api_urls",
            blockchain_rid: blockchainRid
                ? blockchainRid
                : yield getBrid(directoryNodeURLPool[0], blockchainIid),
        };
        const rest = createRestClient(directoryNodeURLPool, directoryBRID);
        const baseUrls = yield rest.query(queryObject);
        if (!baseUrls.length) {
            throw new BlockchainUrlUndefinedException(blockchainRid ? blockchainRid : blockchainIid);
        }
        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();
            }
        });
    });
};
function ensureArray(input) {
    if (typeof input === "string") {
        return [input];
    }
    return input;
}
export const formatTransactionInfoResponse = (transactionInfoResponse) => {
    return {
        blockRid: toBuffer(transactionInfoResponse.blockRID),
        blockHeight: transactionInfoResponse.blockHeight,
        blockHeader: toBuffer(transactionInfoResponse.blockHeader),
        witness: toBuffer(transactionInfoResponse.witness),
        timestamp: transactionInfoResponse.timestamp,
        txRid: toBuffer(transactionInfoResponse.txRID),
        txHash: toBuffer(transactionInfoResponse.txHash),
        txData: toBuffer(transactionInfoResponse.txData),
    };
};
//# sourceMappingURL=utils.js.map