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

import com.pwt.netty.common.charger.ChargerMessage;
import com.pwt.netty.handler.codec.exceptions.ProtocolException;
import com.pwt.netty.util.MessageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 充电机帧解析
 */
@Slf4j
public class ChargerFrameDecoder extends LengthFieldBasedFrameDecoder {
    private static final int  LENGTH_FIELD_OFFSET = 1;
    private static final int  LENGTH_FIELD_LENGTH = 2;

    private static final int  LENGTH_ADJUSTMENT = 18;
    private static final int MAX_LENGTH = 65535;

    public ChargerFrameDecoder() {
        super(MAX_LENGTH, LENGTH_FIELD_OFFSET , LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT,  0);
    }

    // TODO netty协议解析内存泄露

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
//        if (in != null) {
//            log.info("原始报文：{}", MessageUtil.convertByteBufToString(in));
//        }
        if(in.readableBytes() < 1) {
            return null;
        }
        byte type = in.getByte(0);
        if(!ChargerMessage.MESSAGE_DATA_TYPE_MAP.containsKey(type)) {
            throw new ProtocolException(String.format("invalid message type %x", type));
        }
        return super.decode(ctx, in);
    }
}
