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

public class Enemy : MonoBehaviour {

    private GameManager gameManager;

    [Tooltip("Distance in which the enemy will hit")]
    public float hitDistance = 1.5f;

    private NavMeshAgent navMeshAgent;
    private TargetFinder targetFinder;
    
    private GameObject closestPlayer;

    public AudioSource audioSource;
    public GameObject graphics;
    public List<AudioClip> dieSounds = new List<AudioClip>();

    private bool isDead = false;

    void Start() {
        navMeshAgent = GetComponent<NavMeshAgent>();
        targetFinder = GetComponent<TargetFinder>();

        gameManager = FindObjectOfType<GameManager>();
    }

    void Update() {
        if (gameManager.IsGamePaused())
            return;

        FollowPlayer();
    }

    void FollowPlayer() {
        closestPlayer = targetFinder.GetClosest();

        if (closestPlayer != null) {
            navMeshAgent.SetDestination(closestPlayer.transform.position);

            if (Vector3.Distance(transform.position, closestPlayer.transform.position) <= hitDistance)
                Attack(closestPlayer.GetComponent<Player>());
        }
    }

    void Attack(Player player) {
        if (!isDead)
            player.Hit();
    }

    public void Kill() {
        GetComponent<CapsuleCollider>().enabled = false;
        isDead = true;
        gameManager.KillAlien();
        audioSource.PlayOneShot(dieSounds[Random.Range(0, dieSounds.Count)]);
        graphics.SetActive(false);
        navMeshAgent.isStopped = true;
        navMeshAgent.velocity = Vector3.zero;

        StartCoroutine("Delete");
    }

    IEnumerator Delete() {
        yield return new WaitForSeconds(2);
        this.enabled = false;
        Destroy(gameObject);
    }

    public bool IsDead() {
        return isDead;
    }
}
