local ____lualib = require("lualib_bundle")
local __TS__StringTrim = ____lualib.__TS__StringTrim
local ____exports = {}
local readSaveDatFile, tryLoadModData, DEFAULT_MOD_DATA
local ____jsonHelpers = require("functions.jsonHelpers")
local jsonDecode = ____jsonHelpers.jsonDecode
local ____log = require("functions.log")
local log = ____log.log
local logError = ____log.logError
local ____merge = require("functions.merge")
local merge = ____merge.merge
local ____table = require("functions.table")
local iterateTableInOrder = ____table.iterateTableInOrder
local ____types = require("functions.types")
local isString = ____types.isString
local isTable = ____types.isTable
local ____constants = require("classes.features.other.saveDataManager.constants")
local SAVE_DATA_MANAGER_DEBUG = ____constants.SAVE_DATA_MANAGER_DEBUG
function readSaveDatFile(self, mod)
    local renderFrameCount = Isaac.GetFrameCount()
    local ok, jsonStringOrErrMsg = pcall(tryLoadModData, mod)
    if not ok then
        logError((("Failed to read from the \"save#.dat\" file on render frame " .. tostring(renderFrameCount)) .. ": ") .. jsonStringOrErrMsg)
        return DEFAULT_MOD_DATA
    end
    if jsonStringOrErrMsg == nil then
        return DEFAULT_MOD_DATA
    end
    local jsonStringTrimmed = __TS__StringTrim(jsonStringOrErrMsg)
    if jsonStringTrimmed == "" then
        return DEFAULT_MOD_DATA
    end
    return jsonStringTrimmed
end
function tryLoadModData(mod)
    return mod:LoadData()
end
DEFAULT_MOD_DATA = "{}"
function ____exports.loadFromDisk(self, mod, oldSaveData, classConstructors)
    if not mod:HasData() then
        return
    end
    local jsonString = readSaveDatFile(nil, mod)
    local newSaveData = jsonDecode(nil, jsonString)
    if SAVE_DATA_MANAGER_DEBUG then
        log("Converted data from the \"save#.dat\" to a Lua table.")
    end
    iterateTableInOrder(
        nil,
        newSaveData,
        function(____, subscriberName, saveData)
            if not isString(nil, subscriberName) then
                return
            end
            if not isTable(nil, saveData) then
                return
            end
            local oldSaveDataForSubscriber = oldSaveData[subscriberName]
            if oldSaveDataForSubscriber == nil then
                return
            end
            if SAVE_DATA_MANAGER_DEBUG then
                log("Merging in stored data for feature: " .. subscriberName)
            end
            merge(
                nil,
                oldSaveDataForSubscriber,
                saveData,
                subscriberName,
                classConstructors
            )
        end,
        SAVE_DATA_MANAGER_DEBUG
    )
    log("The save data manager loaded data from the \"save#.dat\" file for mod: " .. mod.Name)
end
return ____exports
