using FairyGUI;
using XGame.Framework.Asyncs;

namespace XGame.Framework.FGUI
{
    public class GObjectFromPackageAsync : Async, IGObjectLoadAsync
    {
        private bool _isRemoveAll;
        public string PackageName { get; private set; }
        public string ObjectName { get; private set; }
        public GObject Result { get; private set; }


        public GObjectFromPackageAsync(string pkgName, string objName)
        {
            PackageName = pkgName;
            ObjectName = objName;
            _isRemoveAll = false;
        }
        protected override void OnRemoveAll()
        {
            _isRemoveAll = true;
            Result = null;
        }

        public void Start()
        {
            if (UIPackage.GetByName(PackageName) == null)
            {
                Log.Error($"UIViewLoadFromPackageAsync.Start UIPackage is null. Paqckage:{PackageName} Object:{ObjectName}");
                Completed();
                return;
            }
            UIPackage.CreateObjectAsync(PackageName, ObjectName, (GObject result) =>
            {
                if (result == null)
                {
                    Log.Error($"UIPackage.CreateObjectAsync result is null. Paqckage:{PackageName} Object:{ObjectName}");
                }
                else if (_isRemoveAll)
                {
                    // 该异步已结束
                    Log.Info($"UIPackage.CreateObjectAsync Callback, Async is Stopped. Paqckage:{PackageName} Object:{ObjectName}");
                    result.Dispose();
                }
                else
                {
                    Result = result;
                }
                Completed();
            });
        }
    }
}