package us.myles.ViaVersion.bungee.listeners;

import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.EntityTracker;

import java.lang.reflect.Method;

/*
    This solves the wrong mainhand issue when you join with BungeeCord on a 1.8 server, and switch to a 1.9 or higher.
 */
public class MainHandPatch implements Listener {
    private static Method getSettings = null;
    private static Method setMainHand = null;

    static {
        try {
            getSettings = Class.forName("net.md_5.bungee.UserConnection").getDeclaredMethod("getSettings");
            setMainHand = Class.forName("net.md_5.bungee.protocol.packet.ClientSettings").getDeclaredMethod("setMainHand", int.class);
        } catch (Exception ignored) {
        }
    }

    @EventHandler
    public void onServerConnect(ServerConnectEvent event) {
        // Ignore if it doesn't exist (Like BungeeCord 1.8)
        if (setMainHand == null)
            return;

        UserConnection user = Via.getManager().getConnection(event.getPlayer().getUniqueId());
        if(user == null) return;
        
        try {
            if (user.get(ProtocolInfo.class).getPipeline().contains(Protocol1_9TO1_8.class)) {
                Object settings = getSettings.invoke(event.getPlayer());
                setMainHand.invoke(settings, user.get(EntityTracker.class).getMainHand());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@@ -1269,15 +1269,38 @@
 d ==
+ null %7C%7C getSettings ==
  null)%0A
-
     
@@ -1421,16 +1421,17 @@
       if
+ 
 (user ==
@@ -1445,24 +1445,16 @@
 return;%0A
-        
 %0A       
@@ -1624,24 +1624,129 @@
 tPlayer());%0A
+                if (settings != null) %7B%0A                    if (user.has(EntityTracker.class)) %7B%0A        
             
@@ -1820,24 +1820,64 @@
 ainHand());%0A
+                    %7D%0A                %7D%0A
             

Fix #587