package com.sonic.cow.client.rtc.callback.rts;

import com.alibaba.fastjson.JSON;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 消息解析
 *
 * @description:
 * @author: mzc
 * @date: 2025-08-27 15:13
 **/
public class MessageParse {

    private static final String SUBTITLE_HEADER = "subv";

    public static Subv unpack(String msg) throws Exception {
        // Base64解码
        byte[] data = Base64.getDecoder().decode(msg);

        // 验证数据长度
        if (data.length < 8) {
            throw new Exception("Data invalid");
        }

        // 验证头部
        String dataHeader = new String(data, 0, 4, StandardCharsets.UTF_8);
        if (!SUBTITLE_HEADER.equals(dataHeader)) {
            throw new Exception("Header not match");
        }

        // 验证数据大小
        int dataSize = ((data[4] & 0xFF) << 24) |
                ((data[5] & 0xFF) << 16) |
                ((data[6] & 0xFF) << 8) |
                (data[7] & 0xFF);

        if (dataSize + 8 != data.length) {
            throw new Exception("Size not match");
        }

        // 提取有效数据并反序列化
        byte[] subData = new byte[dataSize];
        System.arraycopy(data, 8, subData, 0, dataSize);

        return JSON.parseObject(subData, Subv.class);
    }
}
