using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class FateAssetManager : MonoBehaviour
{
    public static FateAssetManager Instance;

    void Awake()
    {
        Instance = this;
    }

    public static IEnumerator DownloadTexture(string url, System.Action<Texture2D> callback)
    {
        Texture2D outTex = null;
        Debug.Log("Downloading Texture " + url);
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            outTex = ((DownloadHandlerTexture)www.downloadHandler).texture;
            outTex.wrapMode = TextureWrapMode.Clamp;
        }
        callback(outTex);
    }

    public static IEnumerator DownloadText(string url, System.Action<string> callback, System.Action<float> onProgress = null)
    {
        UnityWebRequest www = UnityWebRequest.Get(url);

        var request = www.SendWebRequest();

        while (!request.isDone)
        {
            onProgress?.Invoke(request.progress);
            yield return 0;
        }

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(url);
            Debug.Log(www.error);
            callback(null);
        }
        else
        {
            var str = www.downloadHandler.text;
            callback(str);
        }
    }

    public static IEnumerator DownloadBundle(string url, System.Action<AssetBundle> callback, System.Action<float> onProgress = null)
    {
        Error.Log(Color.green, $"Downloading bundle from {url}");
        UnityWebRequest www = UnityWebRequest.Get(url);

        var request = www.SendWebRequest();

        while (!request.isDone)
        {
            onProgress?.Invoke(request.progress);
            yield return 0;
        }

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(url);
            Debug.Log(www.error);
            callback(null);
        }
        else
        {
            var bytes = www.downloadHandler.data;
            callback(AssetBundle.LoadFromMemory(bytes));
        }
    }
}
