using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using static DownLoadXRManager;

public class DownLoadURLXRItem : MonoBehaviour
{
    public static Dictionary<string, List<DownLoadConfig>> downLoadingList = new Dictionary<string, List<DownLoadConfig>>();
    public void startDownload(DownLoadConfig config)
    {
        StartCoroutine(ReadStreamingAssetsFile(config));
    }
    IEnumerator ReadStreamingAssetsFile(DownLoadConfig config)
    {
        if (DownLoadXRManager.downLoadCache.ContainsKey(config.data.path))
        {
            config.bytes?.Invoke(DownLoadXRManager.downLoadCache[config.data.path]);
            yield return null;
        }
        else
        {
            if(downLoadingList.ContainsKey(config.data.path))
            {
                downLoadingList[config.data.path].Add(config);
            }
            else
            {
                downLoadingList.Add(config.data.path, new List<DownLoadConfig>());
                downLoadingList[config.data.path].Add(config);
                string filePath = config.data.path;
                Debug.Log("准备下载" + filePath);
                UnityWebRequest www = UnityWebRequest.Get(filePath);
                www.SendWebRequest();

                while (!www.isDone)
                {
                    for (int i = 0;  i <downLoadingList[config.data.path].Count;  i++)
                    {
                        downLoadingList[config.data.path][i].presson?.Invoke(www.downloadProgress);
                    }
                    yield return null;
                }

                if (www.result != UnityWebRequest.Result.ConnectionError && www.isDone)
                {
                    byte[] bytes = www.downloadHandler.data;
                    for (int i = 0; i < downLoadingList[config.data.path].Count; i++)
                    {
                        downLoadingList[config.data.path][i].bytes?.Invoke(bytes);
                    }
                    if (!DownLoadXRManager.downLoadCache.ContainsKey(config.data.path))
                    DownLoadXRManager.downLoadCache.Add(config.data.path, bytes);
                    downLoadingList.Remove(config.data.path);
                }
                else
                {
                    for (int i = 0; i < downLoadingList[config.data.path].Count; i++)
                    {
                        downLoadingList[config.data.path][i].bytes?.Invoke(null);
                    }
                    downLoadingList.Remove(config.data.path);
                }

            }
        }
        Destroy(this.gameObject);
    }
}