using UnityEngine;

[DisallowMultipleComponent]
public sealed class ParticleDisabler : MonoBehaviour {

    private float interval = 0.0f;

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

    private void UpdateInterval(ParticleSystem ps){
        var lifeTime = 0.0f;
        switch(ps.main.startLifetime.mode){
        case ParticleSystemCurveMode.Constant:
            lifeTime = ps.main.startLifetime.constant;
            break;
        case ParticleSystemCurveMode.TwoConstants:
            lifeTime = ps.main.startLifetime.constantMax;
            break;
        case ParticleSystemCurveMode.Curve:
            lifeTime = ps.main.startLifetime.curve.GetMax();
            break;
        case ParticleSystemCurveMode.TwoCurves:
            lifeTime = Mathf.Max(ps.main.startLifetime.curveMin.GetMax(), ps.main.startLifetime.curveMax.GetMax());
            break;
        }
        if(ps.trails.enabled){
            var trailLifeTime = 0.0f;
            switch(ps.trails.lifetime.mode){
            case ParticleSystemCurveMode.Constant:
                trailLifeTime = ps.trails.lifetime.constant;
                break;
            case ParticleSystemCurveMode.TwoConstants:
                trailLifeTime = ps.trails.lifetime.constantMax;
                break;
            case ParticleSystemCurveMode.Curve:
                trailLifeTime = ps.trails.lifetime.curve.GetMax();
                break;
            case ParticleSystemCurveMode.TwoCurves:
                trailLifeTime = Mathf.Max(ps.trails.lifetime.curveMin.GetMax(), ps.trails.lifetime.curveMax.GetMax());
                break;
            }
            lifeTime += trailLifeTime;
        }
        interval = Mathf.Max(lifeTime + ps.main.duration, interval);
    }

    void OnEnable(){
        this.CallWaitForSeconds(interval, () => gameObject.SetActive(false));
    }
}
