using System;
using UnityEngine;
using XGame.Framework.Asset;
using XGame.Framework.Asyncs;

namespace XGame.Framework.UI
{
    internal class UINestedLoadAsync : Async, IAssetLoadAsync<INestedView>
    {
        public string AddressableName => _loadAsync?.AddressableName;

        private IAssetLoadAsync<UINested> _loadAsync;
        private UIKey _nestedKey;
        private Transform _parent;
        private UIContext _context;
        public INestedView Result { get; private set; }
        public UINestedLoadAsync(IAssetLoadAsync<UINested> loadAsync, UIKey nestedKey, Transform 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 nested = _loadAsync.Result;
            if (nested == null)
            {
                Log.Error($"UINested加载失败. Key:{_nestedKey}");
                return;
            }
            var view = Activator.CreateInstance(_nestedKey.UIViewType) as INestedView;
            (view as INestedInternal).Init(_context, nested, false);
            if (_parent != null)
            {
                nested.transform.SetParent(_parent, false);
                nested.transform.position = Vector3.zero;
                view.Enable();
            }
            Result = view;
            Completed();
            Clear();
        }
        private void Clear()
        {
            _loadAsync = null;
            _nestedKey = null;
            _parent = null;
            _context = null;
            Result = null;
        }
    }
}
