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

public class SeekNearest : MonoBehaviour
{
    public string seekerTag = "predator";
    public string targetTag = "prey";
    public float searchRadius = 10f;

    GameObject[] seekers;
    GameObject[] targets;
    void Start()
    {
        // get all objects for both seeker and target tags
        seekers = GameObject.FindGameObjectsWithTag(seekerTag);

        // for every seeker, set it's destination to the nearest target
        foreach(var seeker in seekers)
        {
            // use the search radius to find any nearby objects
            Collider[] colliders = Physics.OverlapSphere(seeker.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(seeker, colliders);

                // set the destination to the target
                seeker.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;
    }

    
    void Update()
    {
        
    }
}
