package com.choodon.learn.netty.tcp.HeartBeatCheck;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class HeartBeatCheckDecoder extends ReplayingDecoder<HeartBeatCheckDecoder.TcpState> {
    public HeartBeatCheckDecoder() {
        super(TcpState.MAGIC);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int length = 0;
        switch (state()) {
            case MAGIC:
                checkMAGIC(in.readShort());
                checkpoint(TcpState.lENGTH);
            case lENGTH:
                length = in.readInt();
                checkpoint(TcpState.BODY);
            case BODY:
                CharSequence msg = in.readCharSequence(length, CharsetUtil.UTF_8);
                checkpoint(TcpState.MAGIC);
                out.add(msg);
                break;
            default:
                throw new Exception("报文乱码错误");
        }

    }

    private void checkMAGIC(short magic) throws Exception {
        if (magic != 250) {
            throw new Exception("非法消息");
        }

    }

    private void checklENGTH(int lenght) throws Exception {
        if (lenght < 1) {
            throw new Exception("报文长度错误");
        }

    }


    public enum TcpState {
        MAGIC,
        lENGTH,
        BODY
    }
}
