using UnityEngine;
using System.Collections;

[RequireComponent(typeof(ConstantForce))]
public class Rocket : MonoBehaviour {
	
	public float timeOut = 3.0f;
	public GameObject explosionParticle;
	public float explosionRadius = 50;
	public float explosionForce = 1000;
	ParticleSystem _smokeTrail;

	//NEW - set damage for this rocket
	float _damage = 20f;
	//Get - Set Damage
	public float damage {
		get { return _damage; }
		set { _damage = value; }
	}
	
	void Awake () {
		_smokeTrail = GetComponentInChildren<ParticleSystem>();
	}
	
	void Start () {
		Invoke("KillObject", timeOut);
	}
	
	void OnCollisionEnter (Collision others) {
		ContactPoint contactPoint = others.contacts[0];
		Quaternion rotation = Quaternion.Euler(Vector3.up);
		GameObject.Instantiate(explosionParticle, contactPoint.point, rotation);

		//Get the transfrom position of the rocket
		Vector3 position = transform.position;
		//Get all colliders that touches or insides the explosion radius
		Collider[] hits = Physics.OverlapSphere(position, explosionRadius);
		foreach (Collider c in hits) {
            // Check tag
            //if (c.gameObject.tag == null) continue;
			if (c.gameObject.CompareTag("Destructible")) {
				//Get all rigidbodys of the colliders
				Rigidbody r = c.GetComponent<Rigidbody>();
				if (r != null) {
					//Explosion
					r.isKinematic = false;
					r.AddExplosionForce(explosionForce, position, explosionRadius);
				}
			}
		}
	
		KillObject();
	}
	
	void KillObject () {
		if (_smokeTrail != null) {
			_smokeTrail.Stop();
			_smokeTrail.loop = false;
		}
		GameObject.Destroy(gameObject);
	}
}
