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

public class FleeNearestSingle : MonoBehaviour
{

    public string targetTag = "predator";
    public float searchRadius = 15f;
    public float fleeDistance = 10f;

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

    void Start()
    {
        UpdateFlee();
    }

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

    void UpdateFlee()
    {
        // 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 = GetFleeDestination(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 GetFleeDestination(GameObject fleer, Collider[] colliders)
    {
        // go the opposite of the combined target directions
        // (assuming targets are would attempt to go straight at this position)
        Vector3 fleeDir = Vector3.zero;
        foreach (var collider in colliders)
        {
            if (collider.tag == targetTag)
                fleeDir += (transform.position - collider.gameObject.transform.position);
        }

        Vector3 fleeDestination = fleer.transform.position + fleeDir.normalized * fleeDistance;

        return fleeDestination;
    }
}
