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

[ExecuteInEditMode]
public class SetWebGLText : MonoBehaviour
{
    public static SetWebGLText Instance;
    public static Font webglfont;
 //   public Font font;
    // Start is called before the first frame update
    void Awake()
    {
        Instance = this;
     //   webglfont = font;
      //  StartCoroutine(LoadAB());
    }


    IEnumerator DownloadImageMac(callback url)
    {
        string filePath = url.url;

        if (!stlist.ContainsKey(url.url))
        {
            if (System.IO.File.Exists(filePath))
            {
                Task<byte[]> fileData = System.IO.File.ReadAllBytesAsync(filePath);
                while (!fileData.IsCompleted)
                {
                    yield return null;
                }
                Texture2D texture = new Texture2D(2, 2);
                if (texture.LoadImage(fileData.Result))
                {
                    stlist.Add(url.url, texture);
                    url.msg.Invoke(texture);
                    isload = false;
                }
            }
            else
            {
                isload = false;
                Debug.LogError("Failed to download image   "+ filePath);

            }
        }
        else
        {
            yield return null;
            url.msg.Invoke(stlist[url.url]);
            isload = false;
        }
    }

    public static TaskConfig tc;

    IEnumerator LoadAB()
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "loadab");
        //UnityWebRequest request = UnityWebRequest.Get(filePath);

        using (UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(filePath))
        {
            yield return req.SendWebRequest();
            if (req.error == null)
            {
                AssetBundle ab = (req.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
                tc = ab.LoadAsset<TaskConfig>("task");
             //   UI.SetActive(true);
            }
            else
            {
                Debug.Log(filePath );
            }
        }
    }
    Queue<callbackBD> dlbd = new Queue<callbackBD>();
    public void GetBD(string url, Action<GameObject> msg)
    {
        if (sbdtlist.ContainsKey(url))
        {
            msg.Invoke(sbdtlist[url]);
        }
        else
        {

            callbackBD cb = new callbackBD();
            cb.url = url;
            cb.msg = msg;
            dlbd.Enqueue(cb);
        }
    }
    Queue<callback> dl = new Queue<callback>();
    public void GetTexture(string url,Action<Texture2D> msg)
    {
        if(stlist.ContainsKey(url))
        {
            msg.Invoke(stlist[url]);
        }
        else
        {

            callback cb = new callback();
            cb.url = url;
            cb.msg = msg;
            dl.Enqueue(cb);
        }
    }
    bool isload;
    bool isbdload;
    private void Update()
    {
        if (dl.Count > 0 && !isload)
        {
            isload = true;
            callback cb = dl.Dequeue();
#if UNITY_EDITOR
            StartCoroutine(DownloadImageMac(cb));
#else
            StartCoroutine(DownloadImage(cb));
#endif
        }
        if (dlbd.Count > 0 && !isbdload)
        {
            isbdload = true;
            callbackBD cb = dlbd.Dequeue();

            StartCoroutine(DownloadBD(cb));

        }
    }


    IEnumerator DownloadBD(callbackBD cbd)
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath+"/bd", cbd.url);
        //UnityWebRequest request = UnityWebRequest.Get(filePath);

        using (UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(filePath))
        {
            yield return req.SendWebRequest();
            if (req.error == null)
            {
                AssetBundle ab = (req.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
                GameObject go = GameObject.Instantiate( ab.LoadAsset<GameObject>(cbd.url));
                cbd.msg.Invoke(go);
            }
            else
            {
                Debug.Log(filePath);
            }
        }
    }
    Dictionary<string, Texture2D> stlist = new Dictionary<string, Texture2D>();
    Dictionary<string, GameObject> sbdtlist = new Dictionary<string, GameObject>();

    IEnumerator DownloadImage(callback url)
    {
        if(!stlist.ContainsKey(url.url))
        {
            UnityWebRequest m_webrequest = UnityWebRequestTexture.GetTexture(url.url);
            yield return m_webrequest.SendWebRequest();

            if (m_webrequest.result != UnityWebRequest.Result.Success)
            {
                isload = false;
                Debug.LogError("Failed to download image");
            }
            else
            {


                Texture2D tex = ((DownloadHandlerTexture)m_webrequest.downloadHandler).texture;
                stlist.Add(url.url, tex);
                url.msg.Invoke(tex);
                isload = false;
            }

        }
        else
        {
            yield return null;
            url.msg.Invoke(stlist[url.url]);
            isload = false;
        }
    }

    public class callback
    {
        public string url;
        public Action<Texture2D> msg;
    }




    public class callbackBD
    {
        public string url;
        public Action<GameObject> msg;
    }
}