package com.pwt.netty.common.chargerold;

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

import java.nio.charset.StandardCharsets;

/**
 * @author linyun
 * @version V1.0
 * @Title: ChargerMessageHeader
 * @Description: 充电机header
 * @date 2022/11/15
 **/
@Data
@EqualsAndHashCode
public class ChargerMessageHeader implements Codeable {

    public static final int CHARGER_ADDRESS_LENGTH = 14;

    private int start;
    private int length;
    private int serialNo;
    private String chargerAddress;

    @Override
    public void encode(ByteBuf byteBuf)
    {
        byteBuf.writeShort(getStart());
        byteBuf.writeShort(getLength());
        byteBuf.writeInt(getSerialNo());
        byte[] bytes = getChargerAddress().getBytes(StandardCharsets.US_ASCII);
        byte[] byteToWrite = new byte[CHARGER_ADDRESS_LENGTH];
        int length = 0;
        if(bytes.length < byteToWrite.length) {
            length = bytes.length;
        } else {
            length = byteToWrite.length;
        }
        System.arraycopy(bytes, 0, byteToWrite, 0, length);
        byteBuf.writeBytes(byteToWrite);
    }

    @Override
    public void decode(ByteBuf byteBuf)
    {
        setStart(byteBuf.readShort());
        setLength(byteBuf.readUnsignedShort());
        setSerialNo(byteBuf.readInt());
        setChargerAddress(byteBuf.readCharSequence(CHARGER_ADDRESS_LENGTH, StandardCharsets.US_ASCII).toString());
    }
}
