package com.pwt.netty.common.vehicle2.server;

import com.pwt.netty.common.vehicle2.Vehicle2Message;
import com.pwt.netty.handler.codec.exceptions.ProtocolException;
import com.pwt.netty.util.ByteBufUtil;
import io.netty.buffer.ByteBuf;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public abstract class BaseCommandRequest extends Vehicle2Message {

    private LocalDateTime dateTime;

    private final byte command = 0x55;

    public BaseCommandRequest(byte type) {
        super(type);
    }

    @Override
    public int getProtocolLength() {
        return 33;
    } // 24+9

    @Override
    protected void encodeInternal(ByteBuf byteBuf) {
        if(this.dateTime == null) {
            this.dateTime = LocalDateTime.now();
        }
        byteBuf.writeBytes(ByteBufUtil.dateTime2bytes(dateTime));
        byteBuf.writeByte(command);
    }

    @Override
    protected void decodeInternal(ByteBuf byteBuf) throws Exception{
        byte[] bytes = new byte[ByteBufUtil.VEHICLE_DATE_LENGTH];
        byteBuf.readBytes(bytes);
        this.dateTime = ByteBufUtil.bytes2DateTime(bytes);
        byte command = byteBuf.readByte();
        if(command != this.command) {
            throw new ProtocolException(String.format("invalid command %x", command));
        }
    }
}
