package us.myles.ViaVersion;

import org.bukkit.scheduler.BukkitRunnable;
import us.myles.ViaVersion.api.ViaVersion;
import us.myles.ViaVersion.util.ReflectionUtil;

import java.util.Map;
import java.util.UUID;

public class ViaIdleThread extends BukkitRunnable {
    private final Map<UUID, ConnectionInfo> portedPlayers;
    private final Class<?> idlePacketClass;

    public ViaIdleThread(Map<UUID, ConnectionInfo> portedPlayers) {
        this.portedPlayers = portedPlayers;
        try {
            this.idlePacketClass = ReflectionUtil.nms("PacketPlayInFlying");
        } catch(ClassNotFoundException e) {
            throw new RuntimeException("Couldn't find player idle packet, help!", e);
        }
    }

    @Override
    public void run() {
        for(ConnectionInfo info : portedPlayers.values()) {
            long nextIdleUpdate = info.getNextIdlePacket();
            if(nextIdleUpdate <= System.currentTimeMillis()) {
                try {
                    Object packet = idlePacketClass.newInstance();
                    info.getChannel().pipeline().fireChannelRead(packet);
                } catch(InstantiationException | IllegalAccessException e) {
                    System.out.println("Failed to create idle packet.");
                    if(ViaVersion.getInstance().isDebug()) {
                        e.printStackTrace();
                    }
                } finally {
                    info.incrementIdlePacket();
                }
            }
        }
    }
}

@@ -71,51 +71,8 @@
 le;%0A
-import us.myles.ViaVersion.api.ViaVersion;%0A
 impo
@@ -295,16 +295,14 @@
 nal 
-Class%3C?%3E
+Object
  idl
@@ -308,21 +308,16 @@
 lePacket
-Class
 ;%0A%0A    p
@@ -449,21 +449,25 @@
         
-this.
+Class%3C?%3E 
 idlePack
@@ -526,24 +526,158 @@
         
-%7D catch(
+    idlePacket = idlePacketClass.newInstance();%0A        %7D catch (InstantiationException %7C IllegalArgumentException %7C IllegalAccessException %7C 
 ClassNot
@@ -749,16 +749,21 @@
 n't find
+/make
  player 
@@ -853,16 +853,17 @@
      for
+ 
 (Connect
@@ -977,16 +977,17 @@
       if
+ 
 (nextIdl
@@ -1047,465 +1047,66 @@
     
-try %7B%0A                    Object packet = idlePacketClass.newInstance();%0A                    info.getChannel().pipeline().fireChannelRead(packet);%0A                %7D catch(InstantiationException %7C IllegalAccessException e) %7B%0A                    System.out.println(%22Failed to create 
+info.getChannel().pipeline().fireChannelRead(
 idle
- p
+P
 acket
-.%22
 );%0A
-                    if(ViaVersion.getInstance().isDebug()) %7B%0A                        e.printStackTrace();%0A                    %7D%0A                %7D finally %7B%0A    
     
@@ -1149,26 +1149,8 @@
 ();%0A
-                %7D%0A
     

Optimise ViaIdleThread, use 1 object for all packets. (Quite a big speed up)