using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;


public class Enmy : MonoBehaviour {
  public Transform RutaPatrulla;
  public List<Transform> Ptos;
  private int i = 0;
  private NavMeshAgent a;
  public Transform plyr;
  private GameM gM;
  private int enemyHealth = 3;

  public int Health {
    get { return enemyHealth; }
    private set {
      enemyHealth = value;
      if (enemyHealth <= 0) {
        Destroy(this.gameObject);
        Debug.Log("Enemy destroyed");
      }
    }
  }
  void Start() {
    a = GetComponent<NavMeshAgent>();
    plyr = GameObject.Find("Player").transform;
    gM = GameObject.Find("GameManager").GetComponent<GameM>();
    foreach (Transform child in RutaPatrulla)
      Ptos.Add(child);
    MoveToNext();
  }
  void Update() {
    if (a.remainingDistance < 0.2f && !a.pathPending) {
      MoveToNext();
    }
  }
  void MoveToNext() {
    if (Ptos.Count == 0)
      return;
    a.destination = Ptos[i].position;
    i = (i + 1) % Ptos.Count;
  }

  void OnTriggerEnter(Collider other) {
    if (other.name == "Player") {
      a.destination = plyr.position;
      Debug.Log("Going to the player");
    }
  }
  void OnTriggerExit(Collider other) {
    if (other.name == "Player") {
      Debug.Log("Player out of range");
    }
  }
  void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.name == "Player") {
      gM.Health -= 1;
    }
    if (collision.gameObject.name == "TennisBall(Clone)") {
      Health -= 1;
      Debug.Log("A ball has impacted the enemy");
    }
  }

}