-- LUALOCALS < ---------------------------------------------------------
local minetest, pairs, piredo_api
    = minetest, pairs, piredo_api
-- LUALOCALS > ---------------------------------------------------------

local modname = minetest.get_current_modname()
local modstore = minetest.get_mod_storage()
local api = piredo_api.get_mod_api()

function api.save_player_pos(pos)
	local player = api.mainplayer()
	if not player then return end
	pos = pos or player:get_pos()
	pos.h = pos.h or player:get_look_horizontal()
	pos.v = pos.v or player:get_look_vertical()
	modstore:set_string("savepos", minetest.serialize(pos))
end

local restore_pending
function api.restore_player_pos()
	if restore_pending then return end
	local player = api.mainplayer()
	if not player then return end
	local pos = modstore:get_string("savepos")
	pos = pos and pos ~= "" and minetest.deserialize(pos)
	if not pos then return end
	api.screenfade(player)
	restore_pending = true
	minetest.after(0, function()
			restore_pending = nil
			local nplayer = api.mainplayer()
			if not nplayer then return end
			nplayer:set_pos(pos)
			nplayer:set_look_horizontal(pos.h)
			nplayer:set_look_vertical(pos.v)
		end)
end

do
	local voids = {}
	minetest.register_on_mods_loaded(function()
			for k, v in pairs(minetest.registered_nodes) do
				if v.groups and v.groups[modname .. "_void"]
				and v.groups[modname .. "_void"] > 0 then
					voids[k] = true
				end
			end
		end)
	local voiding = {}
	api.register_playerstep(function(player, dtime, pname)
			local pending = voiding[pname]
			if pending then
				pending = pending + dtime
				voiding[pname] = pending
				if pending < 2 then return end
				voiding[pname] = nil
				return api.restore_player_pos()
			end
			local pos = player:get_pos()
			pos.y = pos.y + player:get_properties().eye_height
			local node = minetest.get_node(pos)
			if not voids[node.name] then return end
			api.screenfade(player, true)
			voiding[pname] = 0
		end)
end
