using UnityEngine;
using System.Collections;

public class EnemyControl : MonoBehaviour {
	public AudioClip deathClip;		// Audioclip that can play when the enemy dies.
	public float deathSpinMin = -100f;			// A value to give the minimum amount of Torque when dying
	public float deathSpinMax = 100f;			// A value to give the maximum amount of Torque when dying
	public float killRadius = 10f;			// Radius within which player is killed.
	public AudioClip eatClip;        // Audioclip that can play when the player gets eaten.
	public bool facingRight = false;
	public GameObject Player;

	private bool frontCheck;		// Check if character is in front of plant.
	private bool alive = true;

	void Update(){
		bool PlayerToLeft = transform.position.x > Player.transform.position.x;
		if (facingRight == PlayerToLeft){
			facingRight = !facingRight;
			Flip ();
		}
		if(!alive) Application.LoadLevel(Application.loadedLevel);
	}

	void OnTriggerEnter2D (Collider2D col) 
	{
		// If it hits the player...
		if(col.tag == "Player")
		{
			// ... find the Player script and call the Die function.
			col.gameObject.GetComponent<PlayerControl>().alive = false;
			AudioSource.PlayClipAtPoint(eatClip, transform.position);
			Player.GetComponent<PlayerControl> ().alive = false;
			StartCoroutine(Kill());
		}
	}

	void Death()
	{

		// Allow the enemy to rotate and spin it by adding a torque.
		GetComponent<Rigidbody2D>().fixedAngle = false;
		GetComponent<Rigidbody2D>().AddTorque(Random.Range(deathSpinMin,deathSpinMax));

		Destroy (this);
		// Play deathClip.
		AudioSource.PlayClipAtPoint(deathClip, transform.position);
	}


	public void Flip()
	{
		// Multiply the x component of localScale by -1.
		Vector3 enemyScale = transform.localScale;
		enemyScale.x *= -1;
		transform.localScale = enemyScale;
	}

	IEnumerator Kill(){
		yield return new WaitForSeconds (3);
		alive = !alive;
	}
}
