package xyz.cottongin.radio247.audio

class RingBuffer(
    private val capacityFrames: Int,
    private val onFrame: (ByteArray) -> Unit
) {
    private val buffer = ArrayDeque<ByteArray>()

    fun write(frame: ByteArray) {
        if (capacityFrames == 0) {
            onFrame(frame)
            return
        }
        if (buffer.size >= capacityFrames) {
            onFrame(buffer.removeFirst())
        }
        buffer.addLast(frame)
    }

    fun flush() {
        while (buffer.isNotEmpty()) {
            onFrame(buffer.removeFirst())
        }
    }

    fun clear() {
        buffer.clear()
    }

    fun drop(maxCount: Int): Int {
        val toDrop = minOf(maxCount, buffer.size)
        repeat(toDrop) { buffer.removeFirst() }
        return toDrop
    }

    val size: Int get() = buffer.size
}
