package org.holer.common.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.holer.common.model.HolerMsg;


public class MsgEncoder extends MessageToByteEncoder<HolerMsg> {
    protected void encode(ChannelHandlerContext ctx, HolerMsg msg, ByteBuf out) throws Exception {
        int bodyLen = 10;
        byte[] uriBytes = null;
        if (null != msg.getUri()) {

            uriBytes = msg.getUri().getBytes();
            bodyLen += uriBytes.length;
        }

        if (null != msg.getData()) {
            bodyLen += msg.getData().length;
        }


        out.writeInt(bodyLen);
        out.writeByte(msg.getType());
        out.writeLong(msg.getSerialNumber());

        if (null != uriBytes) {

            out.writeByte((byte) uriBytes.length);
            out.writeBytes(uriBytes);
        } else {

            out.writeByte(0);
        }

        if (null != msg.getData()) {
            out.writeBytes(msg.getData());
        }
    }
}
