-- LUALOCALS < ---------------------------------------------------------
local error, get_mod_api, minetest, pairs, piredo_player,
      piredo_schems, startswith, string, table, vector
    = error, get_mod_api, minetest, pairs, piredo_player,
      piredo_schems, startswith, string, table, vector
local string_format, string_match, table_sort
    = string.format, string.match, table.sort
-- LUALOCALS > ---------------------------------------------------------

local api = get_mod_api()

function api.putschem(pos, room)
	local roomdata = piredo_schems[room] or error(string_format("room %q not found", room))
	if roomdata.pos then pos = vector.add(pos, roomdata.pos) end
	api.statedb.loaded = api.statedb.loaded or {}
	api.statedb.loaded[minetest.hash_node_position(pos)] =
	(not string_match(room, "^clear_")) and {pos = pos, room = room} or nil
	api.savedb()
	return minetest.place_schematic(pos, roomdata.mts)
end

function api.clearschems()
	if not api.statedb.loaded then return end
	local ppos = piredo_player.mainplayer():get_pos()
	for k, v in pairs(api.statedb.loaded) do
		local size = (string_match(v.room, "^large_")
			or string_match(v.room, "^outside")) and 40 or 20
		if ppos.x < (v.pos.x - 0.5)
		or ppos.z < (v.pos.z - 0.5)
		or ppos.x > (v.pos.x + size + 0.5)
		or ppos.z > (v.pos.z + size + 0.5)
		then
			api.putschem(v.pos, "clear_" .. size)
			api.statedb.loaded[k] = nil
		end
	end
	api.savedb()
end

do
	local sortedschems = {}
	for k in pairs(piredo_schems) do
		sortedschems[#sortedschems + 1] = k
	end
	table_sort(sortedschems)
	function api.find_schematics(prefix)
		local t = {}
		for i = 1, #sortedschems do
			local k = sortedschems[i]
			if startswith(k, prefix) then
				t[#t + 1] = k
			end
		end
		return t
	end
end
