"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleResponse = handleResponse;
exports.createRawErrMsg = createRawErrMsg;
const ref_napi_1 = __importDefault(require("@eleccookie/ref-napi"));
const types_1 = require("../types");
const buffer_1 = require("buffer");
/**
 * Handles the response from an FFI call from libmovevm shared library.
 *
 * @param method - The FFI method to invoke.
 * @param errMsg - A pointer to the ErrMsg structure for capturing errors.
 * @param args - Additional arguments to pass to the method.
 * @returns A Promise resolving with the FFI result or rejecting with an error.
 */
async function handleResponse(method, errMsg, ...args) {
    return new Promise((resolve, reject) => {
        method(errMsg, ...args, (_err, res) => {
            const errorData = errMsg.deref();
            if (errorData && !errorData.is_none) {
                const errorMessage = errorData.ptr
                    .reinterpret(errorData.len)
                    .toString('utf-8');
                return reject(new Error(errorMessage));
            }
            if (!res || res.is_none) {
                return reject(new Error('Unknown error occurred'));
            }
            try {
                const result = parseFFIResult(res);
                resolve(result);
            }
            catch (error) {
                reject(new Error(`Failed to process pointer. Error: ${error instanceof Error ? error.message : 'Unknown processing error'}`));
            }
        });
    });
}
/**
 * Parses the FFI result buffer based on the provided format.
 * @param res - The FFI result struct containing the pointer to result data.
 * @param format - The expected format of the FFI result.
 * @returns Parsed FFI result as a string.
 */
function parseFFIResult(res) {
    const buffer = buffer_1.Buffer.from(res.ptr.reinterpret(res.len).toString('utf-8'));
    return buffer.subarray(0, res.cap).toString('utf-8');
}
/**
 * Creates and initializes a raw ErrMsg structure.
 *
 * @returns A pointer to the initialized ErrMsg structure.
 */
function createRawErrMsg() {
    // allocate memory for ErrMsg structure
    const errMsg = ref_napi_1.default.alloc(types_1.UnmanagedVectorType);
    const rawErrMsg = errMsg.deref();
    rawErrMsg.is_none = true;
    rawErrMsg.ptr = ref_napi_1.default.NULL;
    rawErrMsg.len = 0;
    rawErrMsg.cap = 0;
    return errMsg;
}
//# sourceMappingURL=utils.js.map