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

import com.pwt.netty.common.vehicle1.Vehicle1Message;
import io.netty.buffer.ByteBuf;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import java.nio.charset.StandardCharsets;

@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public final class LoginResponse extends Vehicle1Message {

    /**
     * 登录状态: 成功
     */
    public static final byte STATUS_OK = 0;


    /**
     * 登录状态: 失败
     */
    public static final byte STATUS_ERROR = 1;

    /**
     * 失败原因: 未知VIN
     */
    public static final byte ERROR_UNKNOWN_VIN = 1;

    /**
     * 车辆VIN
     */
    private String vin;

    /**
     * 响应状态. 0 成功; 1 失败
     */
    private byte status;

    /**
     * 失败原因. 0
     */
    private byte errorCode;

    public LoginResponse() {
        super((byte) 0x10);
    }

    @Override
    public void encode(ByteBuf byteBuf) throws Exception {
        byteBuf.writeByte(type);
        if (this.vin == null || this.vin.length() != VIN_LENGTH) {
            // 如果vin不对，发送17个0
            byteBuf.writeCharSequence("00000000000000000", StandardCharsets.US_ASCII);
        } else {
            byteBuf.writeCharSequence(this.getVin(), StandardCharsets.US_ASCII);
        }
        byteBuf.writeByte(status);
        byteBuf.writeByte(errorCode);
    }

    @Override
    public void decode(ByteBuf byteBuf) throws Exception {
        this.vin = byteBuf.readCharSequence(VIN_LENGTH, StandardCharsets.US_ASCII).toString();
        this.status = byteBuf.readByte();
        this.errorCode = byteBuf.readByte();
    }

    @Override
    public int getProtocolLength() {
        return 0x14; // 20
    }
}
