using UnityEngine;
using System.Collections;

public class Boomerang : MonoBehaviour {
	AudioSource boomerang;
	public Vector3 target;
	Vector3 targetDirection;
	float speed = 0.25f;
	GameObject player;
	bool returning;
	bool lastFrameReturning;

	// Use this for initialization
	void Start () {
		boomerang = GetComponent<AudioSource> ();
		player = GameObject.FindGameObjectWithTag ("Player");
		returning = false;
		targetDirection = (target - this.transform.position).normalized * speed;
	}

	// Update is called once per frame
	void Update () {
		if (returning)
		{
			this.transform.Rotate (0, 0, -27.5f);
			targetDirection = (player.transform.position - this.transform.position).normalized * speed * 1.25f;
			this.transform.position += targetDirection;
			this.transform.position = new Vector3 (this.transform.position.x, this.transform.position.y, 0);
			if (Mathf.Abs (player.transform.position.x - this.transform.position.x) < 0.25f && Mathf.Abs (player.transform.position.y - this.transform.position.y) < 0.25f)
			{
				Destroy (this.gameObject);
			}
		}
		else
		{			
			boomerang.Play ();
			this.transform.Rotate (0, 0, 20f);
			this.transform.position += targetDirection;
			this.transform.position = new Vector3 (this.transform.position.x, this.transform.position.y, 0);
			if (Mathf.Abs (target.x - this.transform.position.x) < 0.25f && Mathf.Abs (target.y - this.transform.position.y) < 0.25f)
			{
				returning = true;
				player.GetComponent<BoomerangUpgrade> ().canThrowBoomerang = true;
			}
		}
		lastFrameReturning = returning;
	}
}
