-- LUALOCALS < ---------------------------------------------------------
local minetest, piredo_api, piredo_player, piredo_schems, vector
    = minetest, piredo_api, piredo_player, piredo_schems, vector
-- LUALOCALS > ---------------------------------------------------------

local api = piredo_api.get_mod_api()

local oldroom
local function promenades(ppos, room, roompos, roommax)
	local margin = oldroom == room and 0.5 or 2.5
	if ppos.x - margin < roompos.x then return room, "hall_x_minus" end
	if ppos.z - margin < roompos.z then return room, "hall_z_minus" end
	if ppos.x + margin > roommax.x then return room, "hall_x_plus" end
	if ppos.z + margin > roommax.z then return room, "hall_z_plus" end
	oldroom = room
	return room
end

local oldoutside
local function outsidestate(mypos, _, room)
	if mypos.z > 40.5 then return room, "promenade" end
	local zthresh = oldoutside == "lawn" and 24.5 or 21.5
	if mypos.z > zthresh and mypos.x > 11 and mypos.x < 28 then
		oldoutside = "indoors"
		return room, oldoutside
	end
	oldoutside = "lawn"
	return room, oldoutside
end

local function upstairsify(limit)
	return function(mypos, ppos, room, roompos, roommax)
		if mypos.y >= limit then
			return room, "upstairs"
		end
		return promenades(ppos, room, roompos, roommax)
	end
end

local specials = {
	outside = outsidestate,
	outside_ruined = outsidestate,
	normal_prison = upstairsify(4),
	normal_library = upstairsify(8),
}

function api.get_map_area(player)
	local ppos = player:get_pos()

	local room, roompos, roommax = api.get_current_room()
	if not room then return "none" end

	local spec = specials[room]
	if spec then
		if not ppos then return end
		return spec(vector.subtract(ppos, roompos), ppos, room, roompos, roommax)
	end

	return promenades(ppos, room, roompos, roommax)
end

local noscore_subs = {
	hall_x_minus = true,
	hall_z_minus = true,
	hall_x_plus = true,
	hall_z_plus = true,
	promenade = true,
}
minetest.register_globalstep(function()
		local player = piredo_player.mainplayer()
		if not player then return end
		local room, sub = api.get_map_area(player)
		if sub and noscore_subs[sub] then return end
		local schem = piredo_schems[room]
		if schem and not schem.noscore then
			piredo_player.discover("room:" .. room)
		end

	end)
