using UnityEngine;
using System.Collections;

public class BossScript : MonoBehaviour {
	public Transform Player;
	public bool facingRight = true;
	public float speed = 1.0F;
	private float journeyLength;
	public bool follow = false;
	private bool alive = true;
	public Animator playerAnim;

	void Awake()
	{
		// Setting up references.
		Player = transform.Find("/player_placeholder");
		playerAnim = Player.GetComponent<Animator>();
	}

	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(deathClip, transform.position);
			Player.GetComponent<PlayerControl> ().alive = false;
			StartCoroutine(Kill());
		}
	}

	void Update() {
		if(follow){
			journeyLength = Vector3.Distance(transform.position, Player.position);
			float step = speed * journeyLength *Time.deltaTime;
			transform.position = Vector3.MoveTowards(transform.position, Player.position, step);
			// If the input is moving the player right and the player is facing left...
		}
		bool PlayerToLeft = transform.position.x > Player.transform.position.x;
		if (facingRight == PlayerToLeft){
			facingRight = !facingRight;
			Flip ();
		}
		if(!alive) Application.LoadLevel(Application.loadedLevel);
	}
	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;
	}
}
