using CommonAIClient.Unity.Battle;
using System.Collections.Generic;
using UnityEngine;

namespace CommonAIClient.Unity.Utils
{
    /// <summary>
    /// 需要保证其他地方不会处理对象de删除操作
    /// </summary>
    public class EffectAutoDestroy : MonoBehaviour
    {
        public AssetObjectExt aoeHandler;
        public float duration;

        List<ParticleSystem> mParticles = new List<ParticleSystem>();
        List<Animation> mAnimations = new List<Animation>();
        List<Animator> mAnimators = new List<Animator>();
        bool mDestroyed;

        void Start()
        {
            if (Extensions.NearlyZero(duration))
            {
                duration = 3f;
                gameObject.GetComponentsInChildren<ParticleSystem>(mParticles);
                gameObject.GetComponentsInChildren<Animation>(mAnimations);
                gameObject.GetComponentsInChildren<Animator>(mAnimators);
            }
        }

        void Update()
        {
            if (!mDestroyed)
            {
                duration -= Time.deltaTime;
                if (duration <= 0)
                {
                    DoDestroy();
                }

                TryDestroy();
            }
        }

        public void DoDestroy()
        {
            if (!mDestroyed && aoeHandler != null)
            {
                mDestroyed = true;
                DestroyImmediate(this);
                BattleFactroy.Instance.GameObjectAdapter.Unload(aoeHandler);
            }
        }

        void TryDestroy()
        {
            if (mParticles == null)
            {
                Debug.LogError("");
            }
            foreach (var elem in mParticles)
            {
                if (elem.isPlaying || elem.isPaused)
                    return;
            }

            foreach (var elem in mAnimations)
            {
                if (elem.isPlaying)
                    return;
            }

            foreach (var elem in mAnimators)
            {
                if (elem.GetAnimatorTransitionInfo(0).normalizedTime < 1f)
                    return;
            }

            DoDestroy();
        }
    }
}