using UnityEngine;
using mgaia.Utils;

namespace mgaia.Utils
{
    /// <summary>
    /// Componente que escuta um particle system e dispara eventos
    /// </summary>
    /// <owner>Victor</owner>
    [RequireComponent(typeof(ParticleSystem))]
    public class ParticleSystemEvents : MonoBehaviour
    {
        public delegate void ParticleSystemHandler(ParticleSystem particleSystem);

        public event ParticleSystemHandler OnStartPlaying;
        public event ParticleSystemHandler OnFinishedPlaying;

        private ParticleSystem mParticleSystem;
        private bool? mIsAlive;

        private void Awake()
        {
            mParticleSystem = GetComponent<ParticleSystem>();

            Assert.AssertTrue(mParticleSystem != null, "Não existe um componente ParticleSystem!");
        }

        private void LateUpdate()
        {
            bool isAlive = mParticleSystem.IsAlive();

            if (!mIsAlive.HasValue)
            {
                mIsAlive = isAlive;
            }
            else
            {
                if (mIsAlive.Value != isAlive)
                {
                    if (isAlive)
                    {
                        if (OnStartPlaying != null)
                        {
                            OnStartPlaying(mParticleSystem);
                        }
                    }
                    else
                    {
                        if (OnFinishedPlaying != null)
                        {
                            OnFinishedPlaying(mParticleSystem);
                        }
                    }

                    mIsAlive = isAlive;
                }
            }
        }
    }
}