local mod_name = minetest.get_current_modname()
local mod_path = minetest.get_modpath(mod_name)
local S = minetest.get_translator(mod_name)

--[[
        !!!!    DEPRECATED, DO NOT USE.    !!!!
This has been modified to act as mod storage, but it is still bad,
do not use it under any circumstances.
--]]

local save_path = minetest.get_worldpath()
local function find_backend()
    local file = io.open(save_path .. "/world.mt", "r")
    if not file then
        minetest.chat_send_all("ERROR: CANNOT OPEN world.mt TO CHECK BACKEND. ASSUMING \"sqlite3\".")
        return "sqlite3"
    end
    local content = file:read("*a")
    content = string.split(content, "\n")
    for i, line in pairs(content) do
        local st = string.split(line, " = ")
        if st[1] == "backend" then
            return st[2]
        end
    end
end
local backend = find_backend()

local changes_made = false
world_storage = {
    mod_storage = core.get_mod_storage(),
    data = {},
    get_file = function(self, mode)
        local file = io.open(save_path .. "/_world_storage.txt", mode)
        return file
    end,
    save = function(self)
    end,
    load = function(self)
        local data
        local file = self:get_file("r")
        -- check if old data exists
        local ds = file and file:read("*a")
        if ds and (ds ~= "") then
            data = minetest.deserialize(ds, true)
            file:close()
            file = self:get_file("w")
            file:write("")
            file:close()
            for k, v in pairs(data or {}) do
                self.mod_storage:set_string(k, core.serialize(v))
            end
        end
        if data then
            self.data = data
        end
    end,
    get_key = function(self, key)
        if self.data[key] then return self.data[key] end
        if backend == "dummy" then return nil end
        local ds = self.mod_storage:get_string(key)
        if ds ~= "" then self.data[key] = core.deserialize(ds, true) end
        return self.data[key]
    end,
    set_key = function(self, key, val)
        self.data[key] = val
        local ds
        if val == nil then ds = nil
        else ds = core.serialize(val) end
        if ds == nil then
            self.mod_storage:set_string(key, "")
        elseif (backend ~= "dummy") then
            self.mod_storage:set_string(key, ds)
        end
    end,
}

world_storage:load()
