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