package com.yutou.biliapi.bean.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.common.utils.Log;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class WebSocketBody {
    List<JSONObject> bodyList;

    public WebSocketBody(byte[] bytes) {
        bodyList = new ArrayList<>();
        addBody(bytes, 0);
    }

    private void addBody(byte[] bytes, int offset) {
        if (offset >= bytes.length) {
            return;
        }
        byte[] headerByte = new byte[16];
        System.arraycopy(bytes, offset, headerByte, 0, headerByte.length);
        WebSocketHeader header = new WebSocketHeader(headerByte);
        byte[] data = new byte[header.getDataSize() - header.getHeaderSize()];
        System.arraycopy(bytes, offset + header.getHeaderSize(), data, 0, data.length);
        try {
            bodyList.add(JSONObject.parseObject(new String(data)));
        } catch (Exception e) {
            Log.i(header + "|" + new String(data));
        }
        addBody(bytes, offset + header.dataSize);
    }
}
