using UnityEngine;
using System.Collections;

public class BulletBehavior : MonoBehaviour {

	public float bulletSpeed = 10f;
	public AudioClip bulletExplosionSound;

	private bool dead = false;


	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void FixedUpdate () {

		Vector2 bulletForce;

		if (!dead)
		{
			if (Camera.main.orthographic)
			{
				bulletForce =  Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
			}
			else
			{
				bulletForce =  GetWorldPositionOnPlane(Input.mousePosition, transform.position.z) - transform.position;

			}

	//		bulletForce *= bulletSpeed;
	//		gameObject.GetComponent<Rigidbody2D>().velocity = bulletForce;

			if (bulletForce.magnitude > 0.75f)
			{
				bulletForce.Normalize();
				gameObject.GetComponent<Rigidbody2D>().velocity = bulletForce * bulletSpeed  * 3f;

			}
			else
			{
				if (gameObject.GetComponent<Rigidbody2D>().velocity.magnitude > 4f)
				{
					gameObject.GetComponent<Rigidbody2D>().velocity = Vector2.ClampMagnitude(gameObject.GetComponent<Rigidbody2D>().velocity, 4f);
				}
				gameObject.GetComponent<Rigidbody2D>().AddForce(bulletForce * bulletSpeed);
				
			}
		}
			
	
	}

	void OnTriggerEnter2D (Collider2D collider)
	{
		if (collider.tag == "bounds")
		{
			dead = true;
			GetComponent<AudioSource>().PlayOneShot(bulletExplosionSound);
			StartCoroutine(CreateDestroyExplosion(gameObject, 1f));
			GetComponent<Collider2D>().enabled = false;
			GetComponent<Rigidbody2D>().velocity = Vector2.zero;
			GetComponent<SpriteRenderer>().enabled = false;
			Dictionaries.dictionaries.bulletExists = false;

		}
	}

	public IEnumerator CreateDestroyExplosion (GameObject bullet, float time)
	{
		GameObject bulletExplosion = Instantiate(Resources.Load("Prefabs/bulletExplosion", typeof(GameObject)), bullet.transform.position, Quaternion.identity) as GameObject;
		yield return new WaitForSeconds (time);
		//		Debug.Log("Destroying Explosion!");
		Destroy (bulletExplosion);
		Destroy(gameObject);
		
	}

	public Vector3 GetWorldPositionOnPlane(Vector3 screenPosition, float z)
	{
		Ray ray = Camera.main.ScreenPointToRay(screenPosition);
		Plane xy = new Plane(Vector3.forward, new Vector3(0, 0, z));
		float distance;
		xy.Raycast(ray, out distance);
		return ray.GetPoint(distance);
	}
}
