-- LUALOCALS < ---------------------------------------------------------
local klots, minetest, pairs, rawget, table, tonumber, type, unpack
    = klots, minetest, pairs, rawget, table, tonumber, type, unpack
local table_sort
    = table.sort
-- LUALOCALS > ---------------------------------------------------------

if not klots.editmode then return end

local modgen = rawget(_G, "modgen")
if not (modgen and modgen.export) then return end

local function loadexport(name, lv, ...)
	if not lv then return end
	if type(lv) == "function" then return lv() end
	local queue = {...}
	minetest.chat_send_player(name, "loading level " .. lv)
	local lvdata = klots.leveldata[lv]
	return minetest.emerge_area(lvdata.minp, lvdata.maxp,
		function(_, _, more)
			if more > 0 then return end
			minetest.chat_send_player(name, "exporting level " .. lv)
			return modgen.export(name, lvdata.minp, lvdata.maxp,
				true, true, function()
					return loadexport(name, unpack(queue))
				end)
		end)
end

minetest.register_chatcommand("exportlv", {
		description = "modgen export current level",
		func = function(name)
			local player = minetest.get_player_by_name(name)
			if not player then return false, "invalid player" end

			local pos = player:get_pos()
			local lv = klots.level_from_pos(pos)
			if not tonumber(lv) then return false, "invalid level" end

			return true, loadexport(name, lv)
		end
	})

minetest.register_chatcommand("exportall", {
		description = "modgen export every level",
		func = function(name)
			local queue = {}
			for lv in pairs(klots.leveldata) do
				queue[#queue + 1] = lv
			end
			table_sort(queue)
			queue[#queue + 1] = function()
				return minetest.chat_send_player(name, "EXPORT ALL COMPLETE")
			end
			return true, loadexport(name, unpack(queue))
		end
	})
