-- LUALOCALS < ---------------------------------------------------------
local error, loadfile, minetest, pairs, rawget, rawset, string, unpack
    = error, loadfile, minetest, pairs, rawget, rawset, string, unpack
local string_format, string_sub
    = string.format, string.sub
-- LUALOCALS > ---------------------------------------------------------

local function get_mod_api()
	local modname = minetest.get_current_modname()
	local api = rawget(_G, modname) or {}
	rawset(_G, modname, api)
	return api
end
local api = get_mod_api()
api.get_mod_api = get_mod_api

do
	local included = {}
	function api.include(n)
		local modname = minetest.get_current_modname()
		local modpath = minetest.get_modpath(modname)
		local found = included[n]
		if found ~= nil then return unpack(found) end
		local func, err = loadfile(modpath .. "/" .. n .. ".lua")
		if not func then return error(err) end
		found = {func(api.include)}
		included[n] = found
		return unpack(found)
	end
end

function api.starts_with(str, pref)
	return string_sub(str, 1, #pref) == pref
end

function api.add_groups(name, ...)
	local def = minetest.registered_items[name] or error(name .. " not found")
	local groups = {}
	for k, v in pairs(def.groups) do
		groups[k] = v
	end
	local function addall(x, ...)
		if not x then return end
		groups[x] = 1
		return addall(...)
	end
	addall(...)
	return minetest.override_item(name, {groups = groups})
end

do
	local modsloaded
	local modname = minetest.get_current_modname()
	local translate = minetest.get_translator(modname)
	local knownstrings = {}
	local pending
	minetest.after(0, function() modsloaded = true end)
	function api.translate(str, ...)
		if not knownstrings[str] then
			if modsloaded then
				minetest.log("warning", string_format("late-discovered translation string: %q", str))
			end
			knownstrings[str] = str
			if not pending then
				pending = true
				minetest.after(0, function()
						minetest.safe_file_write(
							minetest.get_worldpath() .. "/translate.json",
							minetest.write_json(knownstrings, true))
						pending = nil
					end)
			end
		end
		return translate(str, ...)
	end
end

api.translated_stats = api.include("translated")
api.version = api.include("version")
