package com.pwt.netty.common.vehicle2old;

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

import java.nio.charset.StandardCharsets;

/***
 * 充电机B协议消息头
 */
@Data
@EqualsAndHashCode
public class Vehicle2MessageHeader implements Codeable {

    public static final int START = 0x682324;
    public static final int VIN_LENGTH = 17;

    public Vehicle2MessageHeader() {
        this.start = START;
    }

    private int start;
    private int length;
    private int opCode;
    private String VIN;

    @Override
    public void encode(ByteBuf byteBuf) {
        byteBuf.writeMediumLE(Vehicle2MessageHeader.START);
        byteBuf.writeShortLE(getLength());
        byteBuf.writeByte(getOpCode());
        byte[] vinBytes = getVIN().getBytes(StandardCharsets.US_ASCII);
        byte[] byteToWrite = new byte[VIN_LENGTH];
        int length;
        if(vinBytes.length < byteToWrite.length) {
            length = vinBytes.length;
        } else {
            length = byteToWrite.length;
        }
        System.arraycopy(vinBytes, 0, byteToWrite, 0,  length);
        byteBuf.writeBytes(byteToWrite);
    }

    @Override
    public void decode(ByteBuf byteBuf) {
        // 跳过start的3字节
        byteBuf.readMediumLE();
        setLength(byteBuf.readUnsignedShortLE());
        setOpCode(byteBuf.readUnsignedByte());
        setVIN(byteBuf.readCharSequence(Vehicle2MessageHeader.VIN_LENGTH, StandardCharsets.US_ASCII).toString());
    }
}
