package xyz.cottongin.radio247.audio

import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test

class RingBufferTest {

    @Test
    fun passthroughWhenCapacityIsZero() {
        val emitted = mutableListOf<ByteArray>()
        val buffer = RingBuffer(0) { emitted.add(it) }

        buffer.write(byteArrayOf(1))
        buffer.write(byteArrayOf(2))
        buffer.write(byteArrayOf(3))

        assertEquals(3, emitted.size)
        assertArrayEquals(byteArrayOf(1), emitted[0])
        assertArrayEquals(byteArrayOf(2), emitted[1])
        assertArrayEquals(byteArrayOf(3), emitted[2])
    }

    @Test
    fun buffersUpToCapacityThenEmitsOldest() {
        val emitted = mutableListOf<ByteArray>()
        val buffer = RingBuffer(2) { emitted.add(it) }

        buffer.write(byteArrayOf(1))
        assertEquals(0, emitted.size)

        buffer.write(byteArrayOf(2))
        assertEquals(0, emitted.size)

        buffer.write(byteArrayOf(3))
        assertEquals(1, emitted.size)
        assertArrayEquals(byteArrayOf(1), emitted[0])
    }

    @Test
    fun flushEmitsRemainingBufferedFrames() {
        val emitted = mutableListOf<ByteArray>()
        val buffer = RingBuffer(2) { emitted.add(it) }

        buffer.write(byteArrayOf(1))
        assertEquals(0, emitted.size)

        buffer.flush()
        assertEquals(1, emitted.size)
        assertArrayEquals(byteArrayOf(1), emitted[0])
    }

    @Test
    fun flushOnEmptyBufferDoesNothing() {
        val emitted = mutableListOf<ByteArray>()
        val buffer = RingBuffer(2) { emitted.add(it) }

        buffer.flush()
        assertEquals(0, emitted.size)
    }
}
