package org.apollo.net.codec.game;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apollo.net.meta.PacketType;
import org.apollo.util.security.IsaacRandom;

/**
 * A {@link MessageToByteEncoder} which encodes in-game packets.
 *
 * @author Graham
 */
public final class GamePacketEncoder extends MessageToByteEncoder<GamePacket> {

	/**
	 * The random number generator.
	 */
	private final IsaacRandom random;

	/**
	 * Creates the {@link GamePacketEncoder}.
	 *
	 * @param random The random number generator.
	 */
	public GamePacketEncoder(IsaacRandom random) {
		this.random = random;
	}

	@Override
	protected void encode(ChannelHandlerContext ctx, GamePacket packet, ByteBuf out) throws Exception {
		PacketType type = packet.getType();
		int payloadLength = packet.getLength();
		if (type == PacketType.VARIABLE_BYTE) {
			if (payloadLength >= 256) {
				throw new Exception("Payload too long for variable byte packet.");
			}
		} else if (type == PacketType.VARIABLE_SHORT) {
			if (payloadLength >= 65_536) {
				throw new Exception("Payload too long for variable short packet.");
			}
		}

		out.writeByte(packet.getOpcode() + random.nextInt() & 0xFF);
		if (type == PacketType.VARIABLE_BYTE) {
			out.writeByte(payloadLength);
		} else if (type == PacketType.VARIABLE_SHORT) {
			out.writeShort(payloadLength);
		}
		out.writeBytes(packet.getPayload());
	}

}
@@ -871,16 +871,19 @@
 ngth();%0A
+%09%09%0A
 %09%09if (ty
@@ -912,27 +912,20 @@
 BLE_BYTE
-) %7B%0A%09%09%09if (
+ && 
 payloadL
@@ -936,25 +936,24 @@
 h %3E= 256) %7B%0A
-%09
 %09%09%09throw new
@@ -1010,21 +1010,16 @@
 ket.%22);%0A
-%09%09%09%7D%0A
 %09%09%7D else
@@ -1060,19 +1060,12 @@
 HORT
-) %7B%0A%09%09%09if (
+ && 
 payl
@@ -1087,17 +1087,16 @@
 _536) %7B%0A
-%09
 %09%09%09throw
@@ -1162,13 +1162,8 @@
 %22);%0A
-%09%09%09%7D%0A
 %09%09%7D%0A

Remove useless if