package com.imdroid.sideslope.message;

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

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Layton
 * @date 2023/2/2 20:50
 */
@Data
@EqualsAndHashCode(callSuper=true)
public class D342LocationMessage extends BaseMessage {
    LocalDateTime originalTime; //补传前记录的时间
    List<BaseMessage> messageList = new ArrayList<>();
    String projectId;
    String fwdId;
    @Override
    public void decodeBody(ByteBuf src) {
        // d3 42 length(2048+6) device_id(4bytes) seq(2bytes) data
        this.len = src.readableBytes(); // total length
        this.header = src.readUnsignedShort();// flag
        src.readUnsignedShort();// d342 length
        this.id = String.valueOf(src.readUnsignedInt());//id
        this.seq = src.readUnsignedShort();

        if(this.len<=15) return;
        short year = src.readUnsignedByte();
        short month = src.readUnsignedByte();
        short day = src.readUnsignedByte();
        short hour = src.readUnsignedByte();
        short minute = src.readUnsignedByte();
        originalTime =  LocalDateTime.of(2000+year,month,day,hour,minute,0);

        // 拆分D341，指针已移动到d341了
        int pos = 15; // head 10,date 5
        int msgLen = 0;
        while(pos+2 < this.len){
            int flag = src.getUnsignedShort(pos);
            // 有时候两个d341会多一些字节，原因未明
            if(flag != 0xD341){
                if(pos+msgLen > this.len) break;
                else {
                    pos++;
                    continue;
                }
            }
            msgLen = src.getUnsignedShort(pos+2);
            msgLen = (msgLen&0x07FF) + 4;
            if(pos+msgLen > this.len) break; //error

            ByteBuf msgBuf = src.slice(pos,msgLen);
            BaseMessage message = new D341LocationMessage();
            message.decode(msgBuf);
            message.setCreateTime(originalTime);
            messageList.add(message);

            // next data
            pos += msgLen;
        }
    }

    @Override
    public boolean shouldDecodeHeader() {
        return false;
    }
}
