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

namespace XGame.Framework.Map
{
    internal class EntityViewLoadAsync<TEntityView> : Async, IEntityViewLoadAsync<TEntityView> where TEntityView : class, IEntityView, new()
    {
        public TEntityView Result { get; private set; }

        public string AddressableName { get; private set; }


        private IAssetLoadAsync<EntityBehaviour> _assetLoadAsync;
        private Transform _parent;
        private IEntityViewHandle _handle;

        public EntityViewLoadAsync(IAssetLoadAsync<EntityBehaviour> assetLoadAsync, Transform parent, IEntityViewHandle handle)
        {
            AddressableName = assetLoadAsync.AddressableName;
            _assetLoadAsync = assetLoadAsync;
            _parent = parent;
            _handle = handle;
            assetLoadAsync.On(OnLoaded);
            _handle = handle;
        }

        private void OnLoaded(IAsync _)
        {
            var behaviour = _assetLoadAsync.Result;
            if (behaviour != null)
            {
                var entityView = _handle.CreateEntity<TEntityView>(behaviour);
                if (_parent != null)
                {
                    behaviour.transform.SetParent(_parent, false);
                }
                entityView.Enable();
                Result = entityView;
            }
            Completed();
            //清理
            Clear();
        }
        protected override void OnRemoveAll()
        {
            _assetLoadAsync?.RemoveAll();
            Clear();
        }
        private void Clear()
        {
            _assetLoadAsync = null;
            _parent = null;
            _handle = null;
        }
    }
}
