package us.myles.ViaVersion.bukkit.listeners.protocol1_9to1_8;

import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.PlayerDeathEvent;
import us.myles.ViaVersion.ViaVersionPlugin;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.ViaVersion;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.bukkit.listeners.ViaBukkitListener;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;

public class DeathListener extends ViaBukkitListener {
    public DeathListener(ViaVersionPlugin plugin) {
        super(plugin, Protocol1_9TO1_8.class);
    }

    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
    public void onDeath(PlayerDeathEvent e) {
        Player p = e.getEntity();
        if (isOnPipe(p) && ViaVersion.getConfig().isShowNewDeathMessages() && checkGamerule(p.getWorld()) && e.getDeathMessage() != null)
            sendPacket(p, e.getDeathMessage());
    }

    public boolean checkGamerule(World w) {
        try {
            return Boolean.parseBoolean(w.getGameRuleValue("showDeathMessages"));
        } catch (Exception e) {
            return false;
        }
    }

    private void sendPacket(final Player p, final String msg) {
        Via.getPlatform().runSync(new Runnable() {
            @Override
            public void run() {
                PacketWrapper wrapper = new PacketWrapper(0x2C, null, getUserConnection(p));
                try {
                    wrapper.write(Type.VAR_INT, 2); // Event - Entity dead
                    wrapper.write(Type.VAR_INT, p.getEntityId()); // Player ID
                    wrapper.write(Type.INT, p.getEntityId()); // Entity ID
                    Protocol1_9TO1_8.FIX_JSON.write(wrapper, msg); // Message

                    wrapper.send(Protocol1_9TO1_8.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

@@ -1479,24 +1479,108 @@
 oid run() %7B%0A
+                // If online%0A                if(getUserConnection(p) != null) %7B%0A    
             
@@ -1668,38 +1668,46 @@
                 
+   
+ 
 try %7B%0A
+    
                 
@@ -1765,16 +1765,20 @@
 ty dead%0A
+    
         
@@ -1860,32 +1860,36 @@
                 
+    
 wrapper.write(Ty
@@ -1923,24 +1923,28 @@
 / Entity ID%0A
+    
             
@@ -2022,32 +2022,36 @@
                 
+    
 wrapper.send(Pro
@@ -2080,32 +2080,36 @@
                 
+    
 %7D catch (Excepti
@@ -2136,16 +2136,20 @@
         
+ 
+   
 e.printS
@@ -2157,24 +2157,46 @@
 ackTrace();%0A
+                    %7D%0A
             

Fix #604