using System;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace XenseAR {

public class ImageLoader
{
    public static event Action OnFinishLoad;
    public async Task<Texture2D> GetTexture(string url)
    {
        Debug.Log("Load Image");
        string urlLoad;
        if (File.Exists(url))
        {
            urlLoad = "file://" + url;
        }
        else
        {
            urlLoad = url;
        }
        UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(urlLoad);
        var operation= uwr.SendWebRequest();
        while (!operation.isDone)
        {
            await Task.Yield();
        }

        if (uwr.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(url + "  " + uwr.error);
            State.Instance.ImageLoaderAgent--;
           // OnFinishLoad?.Invoke();
            return null;
        }
        else
        {
            State.Instance.ImageLoaderAgent--;
           // OnFinishLoad?.Invoke();
            return DownloadHandlerTexture.GetContent(uwr);
            // Get downloaded asset bundle

        }
        

    }
}
}
