using System.Collections;
using UnityEngine;
using matnesis.TeaTime;

public class EnemyBehaviour : MonoBehaviour 
{
	public int lifeAttempts = 1;
	public float moveSpeed;
	public float detectionRate = 0.3f;
	public float detectionDistance = 4f;

	public bool playerDetected;
	private TeaTime detectPlayer;
	private Transform player;
	private Rigidbody rBody;

	private Vector3 currDistance;
	private bool noDamage;

	void Start () 
	{
		player = GameObject.FindGameObjectWithTag(Tags.Player).transform;
		detectPlayer = this.tt ();

		if(moveSpeed > 0)
		{
			detectPlayer.Add (() => 
				{

					float plDistance = Vector3.Distance(player.position, transform.position);
					playerDetected = plDistance < detectionDistance;

					if(playerDetected)
					{
						detectPlayer.Stop();
					}
				}).Add(detectionRate).Repeat().Immutable();
		}

		rBody = GetComponent<Rigidbody> ();
	}
	
	// Update is called once per frame
	void FixedUpdate () 
	{
		if(moveSpeed > 0 && playerDetected)
		{
			Vector3 relativePos = player.position - transform.position;

			currDistance = Vector3.Lerp (currDistance, relativePos.normalized, moveSpeed * Time.deltaTime);
			rBody.velocity = new Vector3 (currDistance.x * moveSpeed,
											rBody.velocity.y,
											rBody.velocity.z);
		}
	}

	void OnCollisionEnter (Collision col)
	{
		if(col.gameObject.tag == Tags.Player || col.gameObject.layer == LayerMask.NameToLayer(Layers.Bullet))
		{

			if(noDamage)
			{
				return;
			}

			// Player damage
			lifeAttempts--;

			if(lifeAttempts <= 0)
			{
				// this enemy death
				gameObject.SetActive(false);
				GameManager.WonMoney(gameObject.name.Contains("flower") ? 0 : 1, transform.position);
			}
			else
			{
				SkinnedMeshRenderer render = GetComponentInChildren<SkinnedMeshRenderer> ();
				this.tt("Inmune").Add(() => 
					{
						noDamage = true;
						render.enabled = false;
					}).Add(0.2f, () => 
						{
							render.enabled = true;
						}).Add(0.2f, () => 
							{
								render.enabled = false;
							}).Add(0.2f, () => 
								{
									render.enabled = true;
								}).Add(0.2f, () => 
									{
										render.enabled = false;
									}).Add(0.2f, () => 
										{
											render.enabled = true;
											noDamage = false;
										});
			}
		}
	}
}
