local S = minetest.get_translator("titou_random_teleport")
local players = {}

minetest.register_privilege("random_teleport", {
    description = S("this permission serves to teleport to a random location.")
})

minetest.register_chatcommand("random_teleport", {
    description = S("this command serves to teleport to a random location."),
    privs = { random_teleport = true },
    func = function(name)
        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, S("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, S("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, S("you have been successfully teleported to a random location."))
                end
            end)

            minetest.after(40, 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, S("you need to wait the delay before use again this command."))
        end
    end,
})
