package com.pwt.netty.handler.codec.vehicle1;

import com.pwt.netty.common.vehicle1.Vehicle1Message;
import com.pwt.netty.handler.codec.exceptions.ProtocolException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class Vehicle1ProtocolEncoder extends MessageToByteEncoder<Vehicle1Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Vehicle1Message msg, ByteBuf out) throws Exception {
        // 使用小端格式
        // frame header
        out.writeShortLE(Vehicle1Message.MAGIC);
        // length
        out.writeByte(msg.getProtocolLength());
        int savedWriteIndex = out.writerIndex();
        msg.encode(out);
        int actualLength = out.writerIndex() - savedWriteIndex;
        if(actualLength != msg.getProtocolLength()) {
            throw new ProtocolException("encode frame error: length value not equals actual data length");
        }
    }
}
