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

local modname = minetest.get_current_modname()
local modstore = minetest.get_mod_storage()
local 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)
	api.register_playerstep(function(player)
			local pos = player:get_pos()
			pos.y = pos.y + player:get_properties().eye_height
			local node = minetest.get_node(pos)
			if voids[node.name] then return api.restore_player_pos() end
		end)
end
