package protocolsupport.api.tab;

import java.io.IOException;

import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;

import net.minecraft.server.v1_8_R3.PacketPlayOutPlayerListHeaderFooter;

import protocolsupport.api.ProtocolVersion;
import protocolsupport.api.chat.ChatAPI;
import protocolsupport.api.chat.components.BaseComponent;
import protocolsupport.api.chat.components.TextComponent;
import protocolsupport.protocol.PacketDataSerializer;

public class TabAPI {

	private static int maxTabSize = Math.min(Bukkit.getMaxPlayers(), 60);

	public static int getMaxTabSize() {
		return maxTabSize;
	}

	public static void setMaxTabSize(int maxSize) {
		maxTabSize = maxSize;
	}


	private static BaseComponent currentHeader;
	private static BaseComponent currentFooter;

	public static void setDefaultHeader(BaseComponent header) {
		currentHeader = header;
	}

	public static void setDefaultFooter(BaseComponent footer) {
		currentFooter = footer;
	}

	public static BaseComponent getDefaultHeader() {
		return currentHeader;
	}

	public static BaseComponent getDefaultFooter() {
		return currentFooter;
	}

	private static final BaseComponent empty = new TextComponent("");

	public static void sendHeaderFooter(Player player, BaseComponent header, BaseComponent footer) {
		PacketDataSerializer serializer = PacketDataSerializer.createNew(ProtocolVersion.getLatest());
		serializer.writeString(ChatAPI.toJSON(header != null ? header : empty));
		serializer.writeString(ChatAPI.toJSON(footer != null ? footer : empty));
		PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter();
		try {
			packet.a(serializer);
		} catch (IOException e) {
		}
		((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
	}

}

@@ -1427,24 +1427,33 @@
 tLatest());%0A
+%09%09try %7B%0A%09
 %09%09serializer
@@ -1515,16 +1515,17 @@
 mpty));%0A
+%09
 %09%09serial
@@ -1593,16 +1593,17 @@
 ty));%0A%09%09
+%09
 PacketPl
@@ -1682,16 +1682,17 @@
 oter();%0A
+%09
 %09%09try %7B%0A
@@ -1694,16 +1694,17 @@
 ry %7B%0A%09%09%09
+%09
 packet.a
@@ -1717,16 +1717,17 @@
 lizer);%0A
+%09
 %09%09%7D catc
@@ -1750,14 +1750,16 @@
 ) %7B%0A
+%09
 %09%09%7D%0A%09%09
+%09
 ((Cr
@@ -1826,14 +1826,57 @@
 acket);%0A
+%09%09%7D finally %7B%0A%09%09%09serializer.release();%0A%09%09%7D%0A
 %09%7D%0A%0A%7D%0A

Fix memory leak in TabAPI