local players = {}

minetest.register_chatcommand("rtp", {
    description = TRANSLATE("this command serves to teleport to a random location."),
    func = function(name)
        local timer = tonumber(1)
        local teleporting = false
        for k, v in pairs(players) do
            if v == name then
                teleporting = true
                break
            end
        end
        if teleporting == false then
            table.insert(players, name)
            local player = minetest.get_player_by_name(name)
            local old_pos = player:getpos()
            local x = math.random(-30000, 30000)
            local y = 0
            local z = math.random(-30000, 30000)
            local pos = vector.new(x, y, z)
            local erreur = false
            player:setpos(pos)
            minetest.chat_send_player(name, TRANSLATE("a good location is currently in search for you...please wait."))
            minetest.after(3, function()
                local node_name = minetest.get_node(player:getpos()).name
                while node_name ~= "air" do
                    y = y + 1
                    local pos = vector.new(x, y, z)
                    player:setpos(pos)
                    node_name = minetest.get_node(player:getpos()).name
                    if y > 500 then
                        player:setpos(old_pos)
                        erreur = true
                        break
                    end
                end
                if erreur == true then
                    minetest.chat_send_player(name, TRANSLATE("the random teleportation failed.try again.if the problem persist,maybe the world is not compatible with the mod."))
                else
                    minetest.chat_send_player(name, TRANSLATE("you have been successfully teleported to a random location."))
                end
            end)
            minetest.after(timer, function()
                for k, v in pairs(players) do
                    if v == name then
                        table.remove(players, k)
                        break
                    end
                end
            end)
        else
            minetest.chat_send_player(name, TRANSLATE("you need to wait the delay before use again this command."))
        end
    end,
})
