package com.pwt.netty.common.chargerold;

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

/**
 * @author linyun
 * @version V1.0
 * @Title: ChargerMessage
 * @Description: 充电机协议
 * @date 2022/11/15
 **/
@Data
@EqualsAndHashCode
public abstract class ChargerMessage<T extends MessageData> implements Codeable {

    private ChargerMessageHeader header;
    private T messageData;
    private int end;

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

    @Override
    public final void encode(ByteBuf byteBuf)
    {
        header.encode(byteBuf);
        messageData.encode(byteBuf);
        byteBuf.writeByte(end);
    }

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