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

public class Projectile : MonoBehaviour {
    
    public float projectileSpeed = 10f;
    public float lifetime = 10f;

    private GameObject target;

    private NavMeshAgent agent;

    private Vector3 direction;

    public ParticleSystem ps;
    public GameObject graphics;

    public AudioSource audioSource;

    void Start() {
        agent = GetComponent<NavMeshAgent>();

        StartCoroutine("DelayedDeath");
    }

    void FixedUpdate() {
        if (target != null)
            FollowTarget();
    }

    IEnumerator DelayedDeath() {
        yield return new WaitForSeconds(lifetime);
        Explode();
    }

    void FollowTarget() {
        if (target == null || target.GetComponent<Enemy>() == null || target.GetComponent<Enemy>().IsDead())
            SetTarget(GetComponent<TargetFinder>().GetClosest());
        agent.SetDestination(target.transform.position);
    }

    public void SetTarget(GameObject target) {
        if (target != null)
            this.target = target;
    }

    void Explode() {
        audioSource.Play();
        agent.velocity = Vector3.zero;
        agent.isStopped = true;
        graphics.SetActive(false);
        ps.Play();

        StartCoroutine("Delete");
    }

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

    void OnCollisionEnter(Collision collision) {
        if (collision.gameObject.tag == "Enemy") {
            collision.gameObject.GetComponent<Enemy>().Kill();
            Explode();
        }
        else if (collision.gameObject.tag == "Projectile") {
            Explode();
        }
    }
}
