-- LUALOCALS < ---------------------------------------------------------
local core, error, loadfile, rawget, rawset, string, unpack
    = core, error, loadfile, rawget, rawset, string, unpack
local string_sub
    = string.sub
-- LUALOCALS > ---------------------------------------------------------

local modname = core.get_current_modname()

-- Require HTTP API (must be done at module scope)
local http = core.request_http_api()
if not http then
	return error(modname .. " must be in secure.http_mods in luanti.conf")
end

-- Create public export object.
local arclib = rawget(_G, modname) or {}
rawset(_G, modname, arclib)

-- A function like "require" to load a submodule (lua file) relative
-- to the mod root path only once, reusing past results. The included
-- file is given certain shared data as the first arg of `...`, which
-- is how we're able to share the HTTP API with our components without
-- leaking it to other mods.
local include
do
	local modpath = core.get_modpath(modname)
	local included = {}
	local shared = {
		arclib = arclib,
		http = http,
	}
	include = function(rel)
		local fullpath = modpath .. "/" .. rel
		if string_sub(fullpath, -4) ~= ".lua" then
			fullpath = fullpath .. ".lua"
		end
		local found = included[fullpath]
		if found then return unpack(found) end
		local func, err = loadfile(fullpath)
		if not func then error(err) end
		local loaded = {func(shared)}
		included[fullpath] = loaded
		return unpack(loaded)
	end
	shared.include = include
end

-- Export all components/layers, though we expect consumers
-- mostly only to use certain layers.
arclib.util = include("util")
arclib.websocket = include("websocket")
arclib.connection = include("connection")
arclib.manager = include("manager")
arclib.ux = include("ux")
