using SDL2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using testdrid.SdlWrapper;

namespace SDL2Demo.SdlWrapper
{
    internal class SoundPlayer
    {

        private static uint audioDevice;
        private static bool openedAudioDevice;

        public static void PlaySoundFile(string filename)
        {
            FileInfo fi = new FileInfo(filename);
            if (!fi.Exists)
                return;

            SDL2.SDL.SDL_AudioSpec audioSpec;
            IntPtr audioBuffer;
            uint audioLength;

            IntPtr result = SDL2.SDL.SDL_LoadWAV(fi.FullName, out audioSpec, out audioBuffer, out audioLength);
            if (result == IntPtr.Zero)
                throw SdlException.GenerateException();

            if (!openedAudioDevice)
            {
                SDL.SDL_AudioSpec desired = new SDL.SDL_AudioSpec();
                SDL.SDL_AudioSpec obtained;

                uint deviceId = SDL.SDL_OpenAudioDevice(IntPtr.Zero, 0, ref audioSpec, out obtained, 0);
                if (deviceId == 0)
                    throw SdlException.GenerateException();
                audioDevice = deviceId;
                openedAudioDevice = true;
            }

            int success = SDL2.SDL.SDL_QueueAudio(audioDevice, audioBuffer, audioLength);
            if (success != 0)
                throw SdlException.GenerateException();

            SDL.SDL_PauseAudioDevice(audioDevice, 0);

            SDL.SDL_FreeWAV(audioBuffer);
        }
    }
}
