package com.yfd.platform.component.nettyserver;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;

public class MyLengthFieldBasedFrameDecoder extends LengthFieldBasedFrameDecoder  {

    private static final int HEADER_SIZE = 19;

    /**
     * @param maxFrameLength  帧的最大长度
     * @param lengthFieldOffset length字段偏移的地址
     * @param lengthFieldLength length字段所占的字节长
     * @param lengthAdjustment 修改帧数据长度字段中定义的值，可以为负数 因为有时候我们习惯把头部记入长度,若为负数,则说明要推后多少个字段
     * @param initialBytesToStrip 解析时候跳过多少个长度
     * @param failFast 为true，当frame长度超过maxFrameLength时立即报TooLongFrameException异常，为false，读取完整个帧再报异
     */


    public MyLengthFieldBasedFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip,boolean failFast) {
        super(ByteOrder.LITTLE_ENDIAN, maxFrameLength,  lengthFieldOffset,  lengthFieldLength,  lengthAdjustment,  initialBytesToStrip,failFast);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx,in);
        MyMessageProtocol msg= new MyMessageProtocol();
        if(frame == null){
            return null;
        }
        if(frame.readableBytes()<HEADER_SIZE){
            throw new Exception("字节数不足");
        }
        byte[] flag1 = new byte[2];
        frame.readBytes(flag1);
        String startflag=new String(HexUtil.encodeHex(flag1,false));
        if(!startflag.equals("EB90")){
            throw new Exception("不符合边缘节点和巡视主机的通讯协议！");
        }
        //读取SenderSerialNo字段
        msg.setSenderSerialNo(frame.readLongLE());

        //读取ReceiverSerialNo字段
        msg.setReceiverSerialNo(frame.readLongLE());

        //读取Sessionflag字段
        msg.setSessionflag(frame.readByte());

        //读取length字段
        int length = frame.readIntLE();
        msg.setXmllen(length);
        //读取body
        byte []bytes = new byte[length];
        frame.readBytes(bytes);
        msg.setXmlcontent(bytes);
        frame.clear();
        in.clear();
        return msg;

    }

}


