-- LUALOCALS < ---------------------------------------------------------
local klots, minetest, vector
    = klots, minetest, vector
-- LUALOCALS > ---------------------------------------------------------

local emerge_radius = 31
emerge_radius = {x = emerge_radius, y = emerge_radius, z = emerge_radius}

local vector_equals = vector.equals
local vector_round = vector.round

local getdata = klots.register_playerstep(function(player, data, dtime)
		if not (data.waitpos and data.topos) then return end
		local loaded = (not data.loading) and minetest.get_node_or_nil(data.topos)
		if loaded and data.cd and data.cd <= 0 then
			if vector_equals(vector_round(player:get_pos()), vector_round(data.topos)) then
				player:get_meta():set_string("last_teleport",
					minetest.serialize(data.topos))
				klots.player_control_set(player, data.topos.control)
				klots.flash_screen(player, "#000000")
				data.cd = nil
				data.waitpos = nil
				data.topos = nil
			else
				klots.player_control_apply(player, function(obj)
						obj:set_pos(data.topos)
						obj:set_velocity({x = 0, y = 0, z = 0})
					end)
			end
		else
			data.cd = (data.cd or 2) - dtime
			if not loaded then
				if not data.loading then
					data.loading = true
					minetest.emerge_area(
						vector.subtract(data.topos, emerge_radius),
						vector.add(data.topos, emerge_radius),
						function(_, _, rem)
							data.loading = rem > 0 or nil
						end)
				end
			end
			klots.player_control_set(player, "frozen")
			klots.player_control_apply(player, function(obj)
					obj:set_pos(data.waitpos)
					obj:set_velocity({x = 0, y = 0, z = 0})
				end)
			klots.flash_screen(player, "#000000", true)
		end
	end)

function klots.player_teleport(player, waitpos, topos)
	local data = getdata(player)
	data.waitpos = waitpos
	data.topos = topos
end
