"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJSONWithNumericString = parseJSONWithNumericString;
exports.stringifyJSONWithNumericString = stringifyJSONWithNumericString;
exports.jsonReplacerWithBigNumbers = jsonReplacerWithBigNumbers;
exports.jsonReviverWithBigNumbers = jsonReviverWithBigNumbers;
exports.jsonReplacerWithBigInts = jsonReplacerWithBigInts;
exports.jsonReviverWithBigInts = jsonReviverWithBigInts;
const BigNumberUtils_1 = require("./BigNumberUtils");
const TypeGuards_1 = require("./TypeGuards");
function parseJSONWithNumericString(jsonString) {
    try {
        return JSON.parse(jsonString, (_key, value) => {
            if (typeof value === "number") {
                return String(Math.floor(value));
            }
            return value;
        });
    }
    catch {
        return undefined;
    }
}
function stringifyJSONWithNumericString(obj) {
    return JSON.stringify(obj, (_key, value) => {
        if (typeof value === "object" && value !== null && value.type === "BigNumber") {
            return BigNumberUtils_1.BigNumber.from(value).toString();
        }
        else if (typeof value === "bigint" && value !== null) {
            return value.toString();
        }
        return value;
    });
}
function jsonReplacerWithBigNumbers(_key, value) {
    if (!(0, TypeGuards_1.isDefined)(value)) {
        return value;
    }
    if (BigNumberUtils_1.BigNumber.isBigNumber(value) || typeof value === "bigint") {
        return value.toString();
    }
    const recordValue = value;
    if (recordValue.type === "BigNumber" && (0, TypeGuards_1.isDefined)(recordValue.hex)) {
        return BigNumberUtils_1.BigNumber.from(recordValue.hex).toString();
    }
    return value;
}
function jsonReviverWithBigNumbers(_key, value) {
    if (typeof value === "string" && /^-?\d+$/.test(value)) {
        const bigNumber = BigNumberUtils_1.BigNumber.from(value);
        if (bigNumber.toString() === value) {
            return bigNumber;
        }
    }
    return value;
}
function jsonReplacerWithBigInts(_key, value) {
    return typeof value === "bigint" ? value.toString() + "n" : value;
}
function jsonReviverWithBigInts(_key, value) {
    return typeof value === "string" && /^-?\d+n$/.test(value) ? BigInt(value.slice(0, -1)) : value;
}
//# sourceMappingURL=JSONUtils.js.map