using FairyGUI;
using System;
using XGame.Framework.Asset;
using XGame.Framework.Asyncs;
using XGame.Framework.UI;

namespace XGame.Framework.FGUI
{
    internal class FguiNestedLoadAsync : Async, IAssetLoadAsync<INestedView>
    {
        private IGObjectLoadAsync _loadAsync;
        private UIKey _nestedKey;
        private GComponent _parent;
        private UIContext _context;
        public string AddressableName => _loadAsync?.ObjectName;

        public INestedView Result { get; private set; }
        public FguiNestedLoadAsync(IGObjectLoadAsync loadAsync, UIKey nestedKey, GComponent parent, UIContext context)
        {
            _loadAsync = loadAsync;
            _nestedKey = nestedKey;
            _parent = parent;
            _context = context;
            loadAsync.On(OnLoaded);
        }

        protected override void OnRemoveAll()
        {
            _loadAsync?.RemoveAll();
            Clear();
        }
        private void OnLoaded(IAsync _)
        {
            var gObject = _loadAsync.Result;
            if (gObject == null)
            {
                Log.Error($"FguiNestedLoadAsync GObject加载失败. Key:{_nestedKey}");
                return;
            }
            var nested = new FguiNested(gObject.asCom);
            var view = Activator.CreateInstance(_nestedKey.UIViewType) as INestedView;
            (view as INestedInternal).Init(_context, nested, false);
            if (_parent != null)
            {
                _parent.AddChild(gObject);
                //全屏UI自适应
                gObject.MakeFullScreen();
                view.Enable();
            }
            Result = view;
            Completed();
            Clear();
        }
        private void Clear()
        {
            _loadAsync = null;
            _nestedKey = null;
            _parent = null;
            _context = null;
            Result = null;
        }

    }
}
