package org.holer.common.util;

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


public class MsgDecoder extends LengthFieldBasedFrameDecoder {
    public MsgDecoder(int maxFrameLen, int lenFieldOffset, int lenFieldLen, int lenAdjustment, int initBytesToStrip) {
        super(maxFrameLen, lenFieldOffset, lenFieldLen, lenAdjustment, initBytesToStrip);
    }


    public MsgDecoder(int maxFrameLen, int lenFieldOffset, int lenFieldLen, int lenAdjustment, int initBytesToStrip, boolean failFast) {
        super(maxFrameLen, lenFieldOffset, lenFieldLen, lenAdjustment, initBytesToStrip, failFast);
    }


    protected HolerMsg decode(ChannelHandlerContext ctx, ByteBuf bin) throws Exception {
        ByteBuf in = (ByteBuf) super.decode(ctx, bin);
        if (null == in) {
            return null;
        }

        if (in.readableBytes() < 4) {
            return null;
        }

        int frameLen = in.readInt();
        if (in.readableBytes() < frameLen) {
            return null;
        }

        HolerMsg hmsg = new HolerMsg();
        hmsg.setType(in.readByte());
        hmsg.setSerialNumber(in.readLong());

        byte uriLen = in.readByte();
        byte[] uriBytes = new byte[uriLen];
        in.readBytes(uriBytes);
        hmsg.setUri(new String(uriBytes));

        int dataLen = frameLen - 1 - 8 - 1 - uriLen;
        byte[] data = new byte[dataLen];
        in.readBytes(data);
        hmsg.setData(data);
        in.release();

        return hmsg;
    }
}
