using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlashGrenadeExplosion : MonoBehaviour {
    [SerializeField]
    private float m_radius = 5.0f;
    [SerializeField]
	private float m_lifetimeInSeconds = 5.0f;
	[SerializeField]
	private AudioClip m_Sound;
    private float m_lifetimeLeft;
    private Spawner m_spawner;
    private bool m_freed = false;

    public float radius
    {
        set { m_radius = value; }
        get { return m_radius; }
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = new Color(0.0f, 1.0f, 0.0f, 0.25f);
        Gizmos.DrawSphere(transform.position, m_radius);
    }

    public void Reset()
    {
        m_lifetimeLeft = m_lifetimeInSeconds;
        GetComponent<ParticleSystem>().Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
        GetComponent<ParticleSystem>().Play(true);
        m_freed = false;
        var sh = transform.FindChild("CircleEffect").GetComponent<ParticleSystem>().shape;
        sh.radius = m_radius;
        transform.FindChild("PointLight").GetComponent<Light>().range = m_radius * 2.0f;

		var audio = GetComponent<AudioSource> ();
		if (audio != null && m_Sound!=null) {
			audio.PlayOneShot (m_Sound, 6f);
		}
    }

    void Awake()
    {
        m_spawner = Util.Find<Spawner>("Spawner");
        Reset();
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        var collidersInRadius = Physics2D.OverlapCircleAll(transform.position, m_radius);

        foreach (var collider in collidersInRadius)
        {
            var soundEmitter = collider.GetComponent<SoundEmitter>();
            if (soundEmitter)
            {
                soundEmitter.Reveal();
            }
        }

        m_lifetimeLeft -= Time.deltaTime;
        if (m_lifetimeLeft <= 0.0f && !m_freed)
        {
            m_spawner.FreeGrenadeExplosion(gameObject, 0.0f, true);
            m_freed = true;
        }
    }
}
