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

local function shareglobal(name, thing)
	return rawget(_G, name) or rawset(_G, name, thing)
end

do
	local included = {}
	shareglobal("include", function(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(include)}
			included[n] = found
			return unpack(found)
		end)
end

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

shareglobal("startswith", function(str, pref) return string_sub(str, 1, #pref) == pref end)

shareglobal("posrel", function(pos, round)
		pos = round and vector.round(pos) or pos
		return function(...) return vector.add(pos, vector.new(...)) end
	end)

shareglobal("addgroups", function(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)
	shareglobal("S", function(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

shareglobal("translated_stats", include("translated"))
