using UnityEngine;
using UnityEngine.Events;

[DisallowMultipleComponent]
public class ParticleEventReceiver : MonoBehaviour {

    [SerializeField]
    private UnityEvent onEnd = default;
    public UnityEvent OnEnd {
        get{ return onEnd; }
    }

    private float interval = 0.0f;
    public float Interval {
        get{ return interval; }
    }
    private Coroutine coroutine;

    void Awake(){
        transform.FindComponent<ParticleSystem>(UpdateInterval);
        transform.FindAllChildrensComponent<ParticleSystem>(UpdateInterval);
    }

    private void UpdateInterval(ParticleSystem ps){
        switch(ps.main.startLifetime.mode){
        case ParticleSystemCurveMode.Constant:
            interval = Mathf.Max(ps.main.startLifetime.constant, interval);
            break;
        case ParticleSystemCurveMode.TwoConstants:
            interval = Mathf.Max(ps.main.startLifetime.constantMin, interval);
            interval = Mathf.Max(ps.main.startLifetime.constantMax, interval);
            break;
        case ParticleSystemCurveMode.Curve:
            interval = Mathf.Max(ps.main.startLifetime.curve.GetMax(), interval);
            break;
        case ParticleSystemCurveMode.TwoCurves:
            interval = Mathf.Max(ps.main.startLifetime.curveMin.GetMax(), interval);
            interval = Mathf.Max(ps.main.startLifetime.curveMax.GetMax(), interval);
            break;
        }
    }

    void OnEnable(){
        coroutine = this.CallWaitForSeconds(interval, onEnd.Invoke);
    }

    void OnDisable(){
        this.SafeStopCoroutine(coroutine);
    }
}
