using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;

namespace qtc_net_client_2.Services
{
    public class AudioService : IDisposable
    {
        public WaveOutEvent? OutputDevice { get; set; }
        public AudioFileReader? AudioFileReader { get; set; }
        public void PlaySoundEffect(string soundName)
        {
            if (!File.Exists($"./Sounds/{soundName}.wav")) return;

            OutputDevice = new WaveOutEvent();
            AudioFileReader = new AudioFileReader($"./Sounds/{soundName}.wav");
            OutputDevice.Init(AudioFileReader);
            OutputDevice.Play();

            return;
        }

        public void PlaySoundLooped(string soundName, int loopCount)
        {
            if (!File.Exists($"./Sounds/{soundName}.wav")) return;

            OutputDevice = new WaveOutEvent();
            AudioFileReader = new AudioFileReader($"./Sounds/{soundName}.wav");
            OutputDevice.Init(AudioFileReader);
            OutputDevice.Play();

            int i = 0;
            OutputDevice.PlaybackStopped += (sender, args) => 
            {
                i++;
                if (i == loopCount) { OutputDevice.PlaybackStopped += null; return; }

                AudioFileReader.Seek(0, SeekOrigin.Begin);
                OutputDevice.Play();
            };
        }

        public void Dispose()
        {
            if (OutputDevice != null) { OutputDevice.Dispose(); OutputDevice = null; }
            if (AudioFileReader != null) { AudioFileReader.Dispose(); AudioFileReader = null; }
        }
    }
}
