package com.pwt.netty.common.vehicle2old;

import com.pwt.netty.common.Codeable;
import io.netty.buffer.ByteBuf;
import lombok.Data;
import lombok.EqualsAndHashCode;

/***
 * 换点控制器B协议消息
 * @param <T> 消息数据
 */
@Data
@EqualsAndHashCode
public abstract class Vehicle2Message<T extends MessageData> implements Codeable {

    public static final int END = 0x68;

    private Vehicle2MessageHeader header;
    private T messageData;
    private int end;

    public abstract Class<T> getMessageDataDecodeClass(int opcode);

    public final void encode(ByteBuf byteBuf) {
        header.encode(byteBuf);
        // 写入数据
        messageData.encode(byteBuf);
        byteBuf.writeByte(end);
    }


    public final void decode(ByteBuf byteBuf) {
        Vehicle2MessageHeader header = new Vehicle2MessageHeader();
        header.decode(byteBuf);
        this.header = header;
        Class<T> dataClazz = getMessageDataDecodeClass(header.getOpCode());
        T data;
        try {
            data = dataClazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        data.decode(byteBuf);
        this.messageData = data;
        this.end = byteBuf.readUnsignedByte();
    }
}
