using Core.Interfaces;
using System.Collections.Concurrent;

namespace Parsons.SteamDeck
{
    public class RaylibAudioPlayer : IAudioDevice
    {
        private ConcurrentQueue<float> _sampleQueue = new ConcurrentQueue<float>();

        // 4096 samples provides a perfect ~90ms safety buffer
        private const int MaxBufferSamples = 4096;

        public void AddSample(float sample)
        {
            _sampleQueue.Enqueue(sample);

            // THE FIX: If the CPU outpaces the soundcard, drop the OLDEST sample!
            // This guarantees we never fall behind and the audio stays perfectly synced.
            if (_sampleQueue.Count > MaxBufferSamples)
            {
                _sampleQueue.TryDequeue(out _);
            }
        }

        // Grab absolutely everything we generated this frame
        public float[] GetQueuedSamples()
        {
            int count = _sampleQueue.Count;
            float[] buffer = new float[count];
            for (int i = 0; i < count; i++)
            {
                _sampleQueue.TryDequeue(out buffer[i]);
            }
            return buffer;
        }
    }
}