using UnityEngine;
using System.Collections;

public class MissileScript : MonoBehaviour {
	public float damage;
	public float force;
	public bool forceMode; // true - boom
	public float radius;
	public int id;
	
	public float speed;
	
	public AudioClip boom;
	
	public Object touchEffect;
	
	private float lifetime;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		rigidbody.AddForce(transform.TransformDirection(Vector3.forward*Time.deltaTime*speed),ForceMode.Impulse);
		
		
		Optimization();
	}
	
	void OnCollisionEnter(Collision col)
	{
		Boom ();
	}
	
	void Optimization()
	{
		lifetime+=Time.deltaTime;
		if(lifetime>20)
			Destroy(gameObject);
	}
	
	void Boom()
	{
		if(touchEffect!=null)
		{
			GameObject g =  Instantiate(touchEffect,transform.position,Quaternion.identity) as GameObject;
		}
		
		
		Collider[] colliders = Physics.OverlapSphere(transform.position, radius*4);
		if(GameObject.FindGameObjectWithTag("Player"))
		{
			Transform player=GameObject.FindGameObjectWithTag("Player").transform;
			if(player.GetComponent<UnitStatus>().alive)
			{
				if(Vector3.Distance(transform.position,player.position)<radius)
				{
					float k = 1 - Vector3.Distance(player.position,transform.position)/radius;
					Debug.Log((transform.position-player.transform.position));
					player.GetComponent<UnitStatus>().ApplyDamage(damage*k,id);
					player.GetComponent<PlayerControll>().additionForce = Vector3.Normalize(player.transform.position-transform.position)*k*force*0.33f;
					
				}
			}
		}
		foreach (Collider hit in colliders) 
		{
            if (hit.rigidbody)
			{
				if(hit.rigidbody.GetComponent<UnitStatus>())
				{
					float k = 1 - Vector3.Distance(rigidbody.transform.position,transform.position)/radius;
					hit.rigidbody.GetComponent<UnitStatus>().ApplyDamage(damage*k,id);
				}
				
				if(!hit.transform.GetComponent<MissileScript>())
                	hit.rigidbody.AddExplosionForce(force, transform.position, radius*4,3.0f);
			}
			
        }
		if(boom!=null)
		{
			audio.clip = boom;
			audio.volume = GameOptions.soundVolume;
			audio.Play();
		}
		gameObject.renderer.enabled=false;
		this.enabled=false;
		Destroy(gameObject,0.6f);
	}
}
