package com.pwt.netty.common.vehicle2old;

import io.netty.buffer.ByteBuf;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.time.LocalDateTime;

@Data
@EqualsAndHashCode
public abstract class MessageData{

    private static final int TIME_LENGTH = 8;
    
    private LocalDateTime time = LocalDateTime.now();


    public  void encode(ByteBuf byteBuf) {
        byte[] bytes = new byte[TIME_LENGTH];
        int year = time.getYear();
        int month = time.getMonthValue();
        int day = time.getDayOfMonth();
        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();
        bytes[0] = (byte) (year / 100);
        bytes[1] = (byte) (year % 100);
        bytes[2] = (byte) month;
        bytes[3] = (byte) day;
        bytes[4] = (byte) hour;
        bytes[5] = (byte) minute;
        bytes[6] = (byte) second;
        byteBuf.writeBytes(bytes);
        encodeInternal(byteBuf);
    }

    /***
     * 子类编码
     * @param byteBuf
     */
    protected abstract void encodeInternal(ByteBuf byteBuf);
    public  void decode(ByteBuf byteBuf) {
        byte[] timeByte = new byte[TIME_LENGTH];
        byteBuf.readBytes(timeByte);
        int yearHigh = timeByte[0] & 0XFF;
        int yearLow = timeByte[1] & 0XFF;
        int year = yearHigh * 100 + yearLow;
        int month = timeByte[2] & 0XFF;
        int day = timeByte[3] & 0XFF;
        int hour = timeByte[4] & 0XFF;
        int minute = timeByte[5] & 0XFF;
        int second = timeByte[6] & 0XFF;

        this.time = LocalDateTime.of(year, month, day, hour, minute, second);
        decodeInternal(byteBuf);
    }

    /**
     * 子类解码
     * @param byteBuf
     */
    protected abstract void decodeInternal(ByteBuf byteBuf);
}
