using System;
using System.Threading.Tasks;
using Mox.Shared;
using Retyped;

namespace Mox.Bridge
{
	public class Sound : SoundBase
	{
		private Sound(dom.AudioBuffer _buffer)
		{
			m_Buffer = _buffer;
		}

		public static async Task<Sound> Create(string _sPath)
		{
			if (s_Ctx == null)
			{
				s_Ctx = new dom.AudioContext();
			}

			var arrayBuffer = await AsyncAjax.GetArrayBuffer(_sPath);
			object buffer = await s_Ctx.decodeAudioData(arrayBuffer).ToTask();
			return new Sound(buffer.As<dom.AudioBuffer[]>()[0]);
		}

		public override void Play(bool _bLooped = false)
		{
			if (s_Ctx.state == dom.AudioContextState.suspended)
			{
				s_Ctx.resume();
			}

			if (s_Ctx.state == dom.AudioContextState.suspended)
			{
				return;
			}

			Stop();
			m_Source = s_Ctx.createBufferSource();
			m_Source.buffer = m_Buffer;
			m_Source.connect(s_Ctx.destination);
			m_Source.loop = _bLooped;
			m_Source.start();
		}

		public override void Stop()
		{
			m_Source?.stop();
		}

		private static dom.AudioContext s_Ctx;
		private dom.AudioBufferSourceNode m_Source;
		private dom.AudioBuffer m_Buffer;
	}
}
