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

public class SeekNearestSingle : MonoBehaviour
{
    public string targetTag = "prey";
    public float searchRadius = 15f;

    public bool updateSeek = false;
    public float updateRate = 1f;
    float lastTime = 0;

    void Start()
    {
        UpdateSeek();
    }

    void Update()
    {
        if (updateSeek && Time.time > lastTime + updateRate)
        {
            UpdateSeek();
        }
    }

    void UpdateSeek()
    {
        // only get nearby colliders
        Collider[] colliders = Physics.OverlapSphere(transform.position, searchRadius);

        // make sure there are objects and that one is a target
        if (colliders.Length > 0 && ContainsTargetTag(colliders))
        {
            // get the closest target
            Vector3 targetPosition = GetClosestCollider(gameObject, colliders);

            // set the destination to the target
            GetComponent<NavMeshAgent>().SetDestination(targetPosition);
        }
    }

    bool ContainsTargetTag(Collider[] colliders)
    {
        // check that at least one collider has the target tag
        foreach (var collider in colliders)
        {
            if (collider.CompareTag(targetTag))
                return true;
        }

        return false;
    }

    Vector3 GetClosestCollider(GameObject seeker, Collider[] colliders)
    {
        float minDist = searchRadius; // set a large starting distance
        Vector3 closestPrey = Vector3.zero; // set a default closest to compare with

        // go through every collider
        foreach (var collider in colliders)
        {
            // check distance only if it matches the target tag
            if (collider.CompareTag(targetTag))
            {
                float dist = Vector3.Distance(seeker.transform.position, collider.transform.position);

                // update the minimum distance
                if (dist < minDist)
                {
                    minDist = dist;
                    closestPrey = collider.transform.position;
                }
            }
        }

        // return the position of the closest
        return closestPrey;
    }
}
