package com.imdroid.sideslope.message;

import io.netty.buffer.ByteBuf;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * @author Layton
 * @date 2023/2/2 20:32
 */
@Data
public abstract class BaseMessage {
    protected int header;
    protected String id;
    protected int len;
    protected int seq;
    protected int pps;
    protected LocalDateTime createTime;

    protected int tenantId;//消息所属的租户，在executor里获取

    protected byte[] srcData;//message在线程中处理，需要把channel传递过来的数据拷贝出来

    public void decode(ByteBuf src) {
        this.createTime = LocalDateTime.now();
        if (shouldDecodeHeader()) {
            // read操作会移动ByteBuf内部指针，除D331外，其他都用read来读
            //int packetLen = src.readableBytes();
            this.header = src.readUnsignedShort();

            this.len = src.readUnsignedShort();
            this.seq = this.len >> 11;
            this.len = this.len & 0x7FF;
            this.id = String.valueOf(src.readUnsignedInt());
            /*if (packetLen - 4 != this.len) {
                String msg = (String.format("id[%s],长度字段值[%s]与包的消息体长度[%s]不匹配", id, this.len, packetLen - 4));
                WrongMessageRecorder.INSTANCE.append("receive wrong message," + msg);
            }*/
            this.pps = src.readUnsignedShort();
        }
        decodeBody(src);
    }

    public abstract void decodeBody(ByteBuf src);

    public boolean shouldDecodeHeader() {
        return true;
    }
}
