using System;
using System.Threading.Tasks;
using Bridge;
using Bridge.Html5;
using Retyped;

namespace Mox.Bridge
{
	public class AsyncAjax : IPromise
	{
		public AsyncAjax(string _sUrl)
		{
			m_sUrl = _sUrl;
		}

		public static Task<byte[]> Get(string _sUrl)
		{
			return Task.FromPromise<byte[]>(new AsyncAjax(_sUrl), (Func<object, byte[]>)(a => 
				                                ArrayFrom(new Uint8Array(a))));
		}

		public static Task<es5.ArrayBuffer> GetArrayBuffer(string _sUrl)
		{
			return Task.FromPromise<es5.ArrayBuffer>(new AsyncAjax(_sUrl), (Func<object, es5.ArrayBuffer>)(a => 
				                                         a.As<es5.ArrayBuffer>()));
		}

		public void Then(Delegate _fulfilledHandler, Delegate _errorHandler = null, Delegate _progressHandler = null)
		{
			var req = new XMLHttpRequest();
			req.ResponseType = XMLHttpRequestResponseType.ArrayBuffer;
			req.Open("GET", m_sUrl);
			req.OnLoad = e => _fulfilledHandler.Call(this, req.Response);
			req.Send();
		}

		[Template("Array.from({value})")]
		public static extern byte[] ArrayFrom (Uint8Array value);

		private readonly string m_sUrl;
	}
}
