using FairyGUI;
using XGame.Framework.Asyncs;

namespace XGame.Framework.FGUI
{
    /// <summary>
    /// 自定义加载，加载UIPackage之外的资源
    /// 貌似只有贴图有效
    /// 该类由UIModuleFGUI创建
    /// </summary>
    public class CustomLoader : GLoader
    {

        private IGloaderHandle _handle;

        private IAsync _loadingAsync;

        public CustomLoader(IGloaderHandle handle)
        {
            _handle = handle;
        }
        protected override void OnUrlChanged()
        {
            _loadingAsync?.RemoveAll();
            _loadingAsync = null;
        }
        protected override void LoadExternal()
        {
            var addressable = this.url;
            _loadingAsync?.RemoveAll();
            _loadingAsync = null;

            var loadAsync = _handle.LoadNTexture(addressable);
            _loadingAsync = loadAsync;
            loadAsync.On(_ =>
            {
                _loadingAsync = null;
                var result = _handle.GetNTexture(addressable);
                if (result == null)
                {
                    //Log.Error($"CustomLoader failed. addressable:{addressable}");
                    this.onExternalLoadFailed();
                    return;
                }
                //Log.Debug($"CustomLoader LoadSuccess Name:{addressable} url:{url} texture:{result.nativeTexture.name}");
                this.onExternalLoadSuccess(result);

            });
            //IconManager.inst.LoadIcon(this.url, OnLoadSuccess, OnLoadFail);
        }

        protected override void FreeExternal(NTexture texture)
        {
            texture.ReleaseRef();
            //Log.Debug($"CustomLoader FreeExternal Name: {this.name} Texture:{texture.nativeTexture.name} Ref:{texture.refCount} rootRef:{texture.root.refCount}");
        }

        override public void Dispose()
        {
            //Log.Info($"CustomLoader Dispose.");
            _loadingAsync?.RemoveAll();
            _loadingAsync = null;
            // 先由GLoader触发FreeExternal
            base.Dispose();
            _handle = null;
        }

    }
}