using System;
using System.Collections;
using System.Collections.Generic;
using FairyGUI;
using NBC;
using NBC.Asset;
using UnityEngine;
using UnityEngine.Networking;

namespace NBF
{
    public class XGLoader : GLoader
    {
        private static Dictionary<string, Texture2D> _loaderInfo = new Dictionary<string, Texture2D>();

        // private AssetProvider _provider;

        // ReSharper disable Unity.PerformanceAnalysis
        private Texture _texture;

        protected override void LoadExternal()
        {
            if (LoadType() == 1)
            {
                LoadExternalSync(url);
            }
            else
            {
                Log.Info($"LoadExternal={url}");
                // _texture = Resources.Load<Texture>(url);
                _texture = Assets.Load<Texture>(url);
                if (_texture != null)
                    onExternalLoadSuccess(new NTexture(_texture));
                else
                    onExternalLoadFailed();
            }
        }

        // ReSharper disable Unity.PerformanceAnalysis
        protected override void FreeExternal(NTexture tex)
        {
            if (LoadType() == 1)
            {
                tex.Unload();
                tex.Dispose();
                _loaderInfo.Remove(url);
                return;
            }

            if (tex.nativeTexture != null)
            {
                // Resources.UnloadAsset(_texture);
            }
        }

        private int LoadType()
        {
            if (!string.IsNullOrEmpty(url) && url.StartsWith("http"))
            {
                return 1;
            }

            return 0;
        }

        private void LoadExternalSync(string downloadUrl)
        {
            Game.Instance.StartCoroutine(DownloadTexture(downloadUrl));
        }

        private IEnumerator DownloadTexture(string downloadUrl)
        {
            var www = UnityWebRequestTexture.GetTexture(downloadUrl);
            yield return www.SendWebRequest();
            if (isDisposed) yield break;
            try
            {
                var texture2D = DownloadHandlerTexture.GetContent(www);
                if (!_loaderInfo.TryAdd(downloadUrl, texture2D))
                {
                    _loaderInfo[downloadUrl] = texture2D;
                }

                if (visible && url.Equals(downloadUrl))
                {
                    onExternalLoadSuccess(new NTexture(texture2D));
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                onExternalLoadFailed();
            }
        }
    }
}