using System;
using Core.Interfaces;
using Microsoft.VisualBasic;
using NAudio.Wave;

namespace Desktop.Audio // Change this to match your project's namespace
{
    public class NAudioPlayer : IAudioDevice
    {
        private WaveOutEvent _waveOut;
        private BufferedWaveProvider _buffer;

        public NAudioPlayer()
        {
            WaveFormat format = WaveFormat.CreateIeeeFloatWaveFormat(44100, 1);

            _buffer = new BufferedWaveProvider(format);

            // THE FIX: Restrict the physical size of the buffer to exactly 100 milliseconds!
            // If the emulator generates audio too fast, the lag can never exceed this limit.
            _buffer.BufferDuration = TimeSpan.FromMilliseconds(100);

            _buffer.DiscardOnBufferOverflow = true;

            _waveOut = new WaveOutEvent();

            // Drop the latency to 50ms for a tighter, snappier response
            _waveOut.DesiredLatency = 50;
            _waveOut.Init(_buffer);
            _waveOut.Play();
        }
        

        public void AddSample(float sample)
        {
            // Convert the float (-1.0f to 1.0f) into 4 raw bytes
            byte[] sampleBytes = BitConverter.GetBytes(sample);

            // Push the 4 bytes to the sound card buffer!
            _buffer.AddSamples(sampleBytes, 0, 4);
        }

        public void Stop()
        {
            _waveOut?.Stop();
            _waveOut?.Dispose();
        }
    }
}