package common.network;

import java.util.zip.Deflater;

import common.net.buffer.ByteBuf;
import common.net.channel.ChannelHandlerContext;
import common.net.handler.codec.MessageToByteEncoder;

public class CompressionEncoder extends MessageToByteEncoder<ByteBuf> {
	private final byte[] buffer = new byte[8192];
	private final Deflater deflater;
	private int treshold;

	public CompressionEncoder(int treshold) {
		this.treshold = treshold;
		this.deflater = new Deflater();
	}

	protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws Exception {
		int len = buffer.readableBytes();
		PacketBuffer pbuf = new PacketBuffer(output);
		if(len < this.treshold) {
			pbuf.writeVarInt(0);
			pbuf.writeBuffer(buffer);
			return;
		}
		byte[] data = new byte[len];
		buffer.readBytes(data);
		pbuf.writeVarInt(data.length);
		this.deflater.setInput(data, 0, len);
		this.deflater.finish();
		while(!this.deflater.finished()) {
			int size = this.deflater.deflate(this.buffer);
			pbuf.writeBytes(this.buffer, 0, size);
		}
		this.deflater.reset();
	}

	public void setTreshold(int treshold) {
		this.treshold = treshold;
	}
}
