using UnityEngine;
using System.Collections;

public class Atomo : MonoBehaviour {

    public float maxExplosionDelay = 3.0f;
    public bool especial = false;

    float explosionDelay = 0f;
    int hitCount = 0;
    AudioSource audioExplosion;

    bool isDestroying = false;

    ParticlePool pool;

    // Use this for initialization
    void Start() {
        explosionDelay = maxExplosionDelay;
        audioExplosion = GetComponent<AudioSource>();
        //GameObject ppool = GameObject.FindGameObjectWithTag("ParticlePool");
        //pool = ppool.GetComponentInChildren<ParticlePool>();
    }

    // Update is called once per frame
    void Update () {
        if (explosionDelay < maxExplosionDelay && !isDestroying) {
            if (explosionDelay <= 0) {
                Explode();
            }

            explosionDelay -= Time.deltaTime;
            print("arrumando o currentDelay para " + explosionDelay);
            
        }

        if (isDestroying && !audioExplosion.isPlaying) {
            Destroy(gameObject);
        }
	}

    void OnTriggerEnter2D(Collider2D other) {
        if (other.gameObject.CompareTag("Particle")) {
            hitCount++;
            if (explosionDelay >= maxExplosionDelay) {
                explosionDelay -= Time.deltaTime;
            }
        }
    }

    //void OnCollisionEnter2D(Collision2D other) {
    //    if (other.collider.gameObject.CompareTag("Particle")) {
    //        Explode();
    //    }
    //}

    void Explode() {
        int numParticulas = 0;
        foreach (Transform t in transform) {
            int rand = Random.Range(0, numParticulas);
            if (t.CompareTag("ShootExit") && (!especial || rand < 3)) {

                GameObject pira = (GameObject) Object.Instantiate(Resources.Load("Particle"), t.position, t.rotation);
                
                pira.SetActive(false);

                Particula pt = pira.GetComponent<Particula>();
                pt.speed = (Mathf.Log(hitCount)+1)*3;

                pira.SetActive(true);

                numParticulas++;

                //pool.Shoot(t.position, t.rotation);
            }
            Destroy(t.gameObject);
        }
        audioExplosion.Play();
        isDestroying = true;
    }
}
