using UnityEngine;
using System.Collections;

public class ParticleEffect : MonoBehaviour {
	
	// Exposed variables
	//--------------------------------	 

    [SerializeField] bool m_destroyAutomatically;
	[SerializeField] bool m_destroyInstantly;
    [SerializeField] float m_startSimulatedOffsetTime;
	
	// Private variables
	//--------------------------------	 

	ParticleSystem m_particleSystem;

    ParticleSystem.Particle[] HACK_ForUnity531f1ParticleBug = new ParticleSystem.Particle[1];

	// Public methods
	//--------------------------------	 
	
	public void StopAndDestroy()
	{
		if (m_destroyInstantly)
		{
			Destroy(gameObject);
		}
		else
		{
			if (m_particleSystem)
			{
				m_particleSystem.Stop();
                m_destroyAutomatically = true;
			}
		}
	}
	
	// Private methods
	//--------------------------------	 

	void Start () 
	{
		m_particleSystem = GetComponent<ParticleSystem>();

		if (m_startSimulatedOffsetTime > 0.0f)
		{
			m_particleSystem.Simulate(m_startSimulatedOffsetTime);
			m_particleSystem.Play();
		}
	}

	void Update () 
	{
		if (m_particleSystem)
		{
			// IsAlive detects if all particles are dead in system
            if (m_destroyAutomatically && !m_particleSystem.IsAlive())
			{
				Destroy (gameObject);
			}
		}
	}

    void LateUpdate()
    {
        GetComponent<ParticleSystemRenderer>().enabled = GetComponent<ParticleSystem>().GetParticles(HACK_ForUnity531f1ParticleBug) > 0;
    }
}
