"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonEncode = exports.jsonDecode = void 0;
const jsonLua = __importStar(require("../lib/jsonLua"));
const log_1 = require("./log");
function tryDecode(jsonString) {
    return jsonLua.decode(jsonString);
}
function tryEncode(luaTable) {
    return jsonLua.encode(luaTable);
}
/**
 * Converts a JSON string to a Lua table.
 *
 * In most cases, this function will be used for reading data from a "save#.dat" file. If decoding
 * fails, it will return a blank Lua table instead of throwing an error. (This allows execution to
 * continue in cases where users have no current save data or have manually removed their existing
 * save data.)
 *
 * Under the hood, this uses a custom JSON parser that was measured to be 11.8 times faster than the
 * vanilla JSON parser.
 */
function jsonDecode(jsonString) {
    const [ok, luaTableOrErrMsg] = pcall(tryDecode, jsonString);
    if (!ok) {
        // Instead of throwing an error, continue execution of the callback.
        (0, log_1.logError)(`Failed to convert the JSON string to a Lua table: ${jsonString}`);
        return new LuaMap();
    }
    return luaTableOrErrMsg;
}
exports.jsonDecode = jsonDecode;
/**
 * Converts a Lua table to a JSON string.
 *
 * In most cases, this function will be used for writing data to a "save#.dat" file. If encoding
 * fails, it will throw an error to prevent writing a blank string or corrupted data to a user's
 * "save#.dat" file.
 *
 * Under the hood, this uses a custom JSON parser that was measured to be 11.8 times faster than the
 * vanilla JSON parser.
 */
function jsonEncode(luaTable) {
    const [ok, jsonStringOrErrMsg] = pcall(tryEncode, luaTable);
    if (!ok) {
        error(`Failed to convert the Lua table to JSON: ${jsonStringOrErrMsg}`);
    }
    return jsonStringOrErrMsg;
}
exports.jsonEncode = jsonEncode;
