using UnityEngine;
using System.Collections;

public class ExplosionCircleAnim : MonoBehaviour {

    public GameObject circlePrefab;
    public GameObject trailPrefab;

    public float circleScaleDuration = 0.5f;
    public float trailScaleDuration = 0.5f;

    public float delayBeforeCircles = 0.1f;
    public float delayBetweenCircles = 0.05f;

    public void PlayExplosion()
    {
        StartCoroutine("ExplosionAnimation");
        if(gameObject.GetComponent<AudioSource>())
        {
            gameObject.GetComponent<AudioSource>().Play();
        }
    }

    /*void Update()
    {
        if(Input.GetKeyDown(KeyCode.I))
        {
            StartCoroutine("ExplosionAnimation");
        }
    }*/

    IEnumerator ExplosionAnimation()
    {
        StartCoroutine("ExplosionTrailAnimation");
        yield return new WaitForSeconds(delayBeforeCircles);
        StartCoroutine("ExplosionCircleAnimation");
    }

    IEnumerator ExplosionCircleAnimation()
    {
        //Circle0
        GameObject circleInstance0 = Instantiate(circlePrefab, transform.position, transform.rotation) as GameObject;
        circleInstance0.transform.parent = transform;
        iTween.ScaleFrom(circleInstance0, iTween.Hash("x", 0, "y", 0, "z", 0, "time", circleScaleDuration, "easetype", iTween.EaseType.linear));
        yield return new WaitForSeconds(delayBetweenCircles);
        //Circle1
        GameObject circleInstance1 = Instantiate(circlePrefab, transform.position, transform.rotation) as GameObject;
        circleInstance1.transform.parent = transform;
        iTween.ScaleFrom(circleInstance1, iTween.Hash("x", 0, "y", 0, "z", 0, "time", circleScaleDuration, "easetype", iTween.EaseType.linear));
        yield return new WaitForSeconds(delayBetweenCircles);
        //Circle2
        GameObject circleInstance2 = Instantiate(circlePrefab, transform.position, transform.rotation) as GameObject;
        circleInstance2.transform.parent = transform;
        iTween.ScaleFrom(circleInstance2, iTween.Hash("x", 0, "y", 0, "z", 0, "time", circleScaleDuration, "easetype", iTween.EaseType.linear));
        yield return new WaitForSeconds(delayBetweenCircles);

        yield return new WaitForSeconds(delayBetweenCircles);
        Destroy(circleInstance0);
        yield return new WaitForSeconds(delayBetweenCircles);
        Destroy(circleInstance1);
        yield return new WaitForSeconds(delayBetweenCircles);
        Destroy(circleInstance2);
    }

    IEnumerator ExplosionTrailAnimation()
    {
        GameObject trailInstance = Instantiate(trailPrefab, transform.position, transform.rotation) as GameObject;
        trailInstance.transform.parent = transform;
        iTween.ScaleFrom(trailInstance, iTween.Hash("x", 0, "y", 0, "z", 0, "time", trailScaleDuration, "easetype", iTween.EaseType.linear));
        yield return new WaitForSeconds(trailScaleDuration);
        Destroy(trailInstance);
    }
}
