-- The functions and variables in this file are only for use in the mod itself.
-- Those that do real work should be local and wrapped in public functions
local function log(text)
    local logmessage = yl_survey.t("log_prefix", yl_survey.modname, text)
    if yl_survey.settings.debug then minetest.log("action", logmessage) end
    return logmessage
end

function yl_survey.log(text) return log(text) end

local function get_savepath()
    local savepath = yl_survey.worldpath .. yl_survey.settings.save_path
    log(yl_survey.t("log_prefix", dump(savepath)))
    return savepath
end

local function get_filepath(filename)
    local path_to_file = get_savepath() .. DIR_DELIM .. filename .. ".json"
    log(yl_survey.t("get_filepath", dump(filename), dump(path_to_file)))
    return path_to_file
end

local function save_json(filename, content)
    if type(filename) ~= "string" or type(content) ~= "table" then
        return false
    end
    local savepath = get_filepath(filename)
    local savecontent = minetest.write_json(content)
    return minetest.safe_file_write(savepath, savecontent)
end

local function load_json(path)
    local file = io.open(path, "r")
    if not file then
        return false, yl_survey.t("error_cannot_open_file", dump(path))
    end

    local content = file:read("*all")
    file:close()

    if not content then
        return false, yl_survey.t("error_cannot_read_file", dump(path))
    end

    return true, minetest.parse_json(content)
end

-- Public functions wrap the private ones, so they can be exchanged easily

function yl_survey.load(filename, ...) return load_json(filename, ...) end

function yl_survey.save(filename, content, ...)
    return save_json(filename, content, ...)
end
