package com.cisdi.data.RFID.gateway;

import com.cisdi.data.common.exception.BusinessException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: 获取完整的报文
 * @Creator: Mo
 * @Date: 2021/6/2 23:37
 */
@Slf4j
public class RfidFrameDecoder extends ByteToMessageDecoder {
    private static final Logger logger = LoggerFactory.getLogger(RfidFrameDecoder.class);

    private RfidTaskStartVo startVo;

    private final static Integer MIN_LENGTH = 10;
    private final byte START_SPLIT = 0x02;
    private final byte END_SPLIT = 0x03;
    private final Set<Integer> validDataSizeInByte = new HashSet<Integer>(Arrays.asList(10));

    public RfidFrameDecoder(RfidTaskStartVo startVo) {
        this.startVo = startVo;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf bufferIn, List<Object> out) throws Exception {
        if (bufferIn.readableBytes() < MIN_LENGTH) {
            return;
        }
        String channelInfo = ctx.toString();

        // 心跳报文为 02 48 65 61 72 74 42 65 61 03 长度10个字节，拥有独立的起始符和结束符，不会和数据报文共享起始符和结束符
        // 数据体长度固定为 8，心跳报文数据内容为 HeartBea
        int beginIndex = bufferIn.readerIndex();

        for (int i = 0; i + 9 < bufferIn.readableBytes(); i += 10) {
            byte  curByte = bufferIn.getByte(beginIndex + i);
            if(curByte != START_SPLIT){
                ctx.close();
                throw new BusinessException(channelInfo + "完整报文第一个字节内容不正确，期望: 0x02,实际：" + curByte);
            }

            byte endByte = bufferIn.getByte(beginIndex + i + 9);
            if(endByte != END_SPLIT){
                ctx.close();
                throw new BusinessException(channelInfo + "完整报文最后一个字节内容不正确，期望: 0x03,实际：" + endByte);
            }

            out.add(bufferIn.retainedSlice(beginIndex + i, 10));
            bufferIn.readerIndex(beginIndex + i + 10);
        }
    }
}
