using StbVorbisSharp;
using Voile.VFS;

namespace Voile.Resources
{
    public class SoundLoader : ResourceLoader<Sound>
    {
        public override IEnumerable<string> SupportedExtensions => new string[]
        {
            ".ogg"
        };

        protected override Sound LoadResource(string path)
        {
            Vorbis vorbis;
            Sound result;

            using var stream = VirtualFileSystem.Read(path);
            byte[] fileBuffer = new byte[stream.Length];
            int bytesRead = stream.Read(fileBuffer, 0, fileBuffer.Length);

            vorbis = Vorbis.FromMemory(fileBuffer);
            vorbis.SubmitBuffer();

            if (vorbis.Decoded == 0)
            {
                vorbis.Restart();
                vorbis.SubmitBuffer();
            }

            var audioShort = vorbis.SongBuffer;
            int length = vorbis.Decoded * vorbis.Channels;

            short[] audioData = new short[length];
            Array.Copy(audioShort, audioData, length);

            result = new Sound(path, audioData)
            {
                Channel = (SoundChannel)vorbis.Channels - 1,
                SampleRate = vorbis.SampleRate,
                BufferSize = length
            };

            vorbis.Dispose();
            return result;
        }
    }
}