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

public class FleeFromTarget : MonoBehaviour
{
    public NavMeshAgent agent;
    public GameObject target;
    public float fleeRadius = 5f;
    public float fleeDistance = 10f;

    public bool trackTargetMovement = false;

    // Time in seconds between checks
    float targetCheckRate = 2f;
    float lastTime = 0;

    void Start()
    {
        CheckForTarget();
    }

    void CheckForTarget()
    {
        // find the target. If within a flee radius, move in opposite direction.

        Vector3 targetPosition = target.transform.position;
        Vector3 thisPosition = transform.position;

        // calculate the difference
        Vector3 fleeVector = thisPosition - targetPosition;
        if (fleeVector.magnitude < fleeRadius)
        {
            Vector3 fleeTarget = thisPosition + fleeVector.normalized * fleeDistance;
            Vector3 fleePosition;

            // try and get a destination
            if(FindDestination(fleeTarget, out fleePosition))
            {
                agent.SetDestination(fleePosition);
            } 
        }
    }

    void Update()
    {
        // every so often reset the destination in case the target has moved
        if (trackTargetMovement && Time.time > lastTime + targetCheckRate)
        {
            CheckForTarget();
            lastTime = Time.time;
        }
    }

    // Function to check if the path valid.
    // Useful to check if destination is on NavMesh

    bool CheckPath(Vector3 destination)
    {
        bool status = true;
        NavMeshPath path = new NavMeshPath();
        agent.CalculatePath(destination, path);

        if (path.status == NavMeshPathStatus.PathInvalid)
            status = false;

        return status;
    }

    bool FindDestination(Vector3 center, out Vector3 result)
    {
        NavMeshHit hit;
        if (NavMesh.SamplePosition(center, out hit, 5.0f, NavMesh.AllAreas))
        {
            result = hit.position;
            return true;
        }
        result = Vector3.zero;
        return false;
    }
}
