using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class Downloader : MonoBehaviour
{
    public static IEnumerator DownloadText(string url, System.Action<string> callback)
    {
        Error.Log("Downloading " + url, Color.green);
        UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(www.error);
            callback?.Invoke("");
        }
        else
        {
            callback?.Invoke(www.downloadHandler.text);
        }
    }

    public static IEnumerator DownloadAsset(string url, string path, System.Action<byte[]> callback)
    {
        Error.Log("Downloading " + url, Color.green);
        using UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError(www.error);
            callback?.Invoke(new byte[0]);
        }
        else
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            File.WriteAllBytes(path, www.downloadHandler.data);
            callback?.Invoke(www.downloadHandler.data);
        }
    }
}
