//
//  SDLSuperFrameParser.swift
//  punchnet
//
//  Created by 安礼成 on 2026/5/22.
//
import Foundation
import NIOCore

final class SDLSuperFrameParser {
    private let allocator = ByteBufferAllocator()
    // 最大缓冲区区为2M
    private let maxPacketSize: Int = 64 * 1024
    private let maxBufferSize: Int
    private var buffer: ByteBuffer
    
    init(maxBufferSize: Int) {
        self.buffer = allocator.buffer(capacity: maxBufferSize)
        self.maxBufferSize = maxBufferSize
    }
    
    // 尝试解析数据
    public func parseFrames(data: Data) throws -> [ByteBuffer] {
        self.buffer.writeBytes(data)
        
        guard buffer.readableBytes >= 2 else {
            return []
        }
        
        var frames: [ByteBuffer] = []
        while true {
            guard let len = buffer.getInteger(at: buffer.readerIndex, endianness: .big, as: UInt16.self) else {
                break
            }
            
            if len > self.maxPacketSize {
                throw SDLSuperError.packetTooLarge
            }
            
            guard buffer.readableBytes >= len + 2 else {
                break
            }
            
            buffer.moveReaderIndex(forwardBy: 2)
            if let buf = buffer.readSlice(length: Int(len)) {
                frames.append(buf)
            }
        }
        
        let threshold = maxBufferSize / 10 * 6
        if buffer.readerIndex > threshold {
            buffer.discardReadBytes()
        }
        
        return frames
    }
    
}
