FrameReassembler.kt

/*
 *
 *  Copyright (C) 2026 Gauthier Le Bartz Lyan (Tritbool)
 *  euc_ble_library — version 1.2.0 — licence GPL-3.0
 *  https://github.com/Tritbool/euc_ble_library
 * /
 */

package io.github.tritbool.euc.ble.frames

import co.touchlab.stately.concurrency.Lock
import co.touchlab.stately.concurrency.withLock

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow

/**
 * Reassembles incoming byte streams into complete frames using a [FrameParser].
 *
 * This class provides a thread-safe way to process incoming BLE data and emit
 * complete frames through a Flow interface.
 *
 * @param parser The frame parser to use for extracting complete frames from byte streams
 */
class FrameReassembler(
    private val parser: FrameParser
) {
    private val lock = Lock()

    private val _frames = Channel<ByteArray>(capacity = FRAME_BUFFER_CAPACITY)
    val frames: Flow<ByteArray> get() = _frames.receiveAsFlow()
    fun observeFrames(): Flow<ByteArray> = frames

    fun reset() {
        lock.withLock { parser.reset() }
    }

    /**
     * Synchronous form: appends [data] and returns the complete frames it produced, in order.
     * Frames returned here are not emitted on [frames]. Prefer this from sync protocols.
     */
    fun feed(data: ByteArray): List<ByteArray> = lock.withLock { parser.appendAndExtract(data) }

    /** Flow form: appends [data] and emits the resulting complete frames on [frames]. */
    fun processIncomingBytes(data: ByteArray) {
        val ready = lock.withLock { parser.appendAndExtract(data) }
        for (frame in ready) {
            check(_frames.trySend(frame).isSuccess) {
                "Frame reassembly output queue is full (capacity=$FRAME_BUFFER_CAPACITY)"
            }
        }
    }

    private companion object {
        const val FRAME_BUFFER_CAPACITY = 256
    }
}