using UnityEngine;
using UnityEngine.AI;

public class AnimalAI : MonoBehaviour
{

    public GameObject followObject;

    public float minXPos;
    public float maxXPos;

    public float minZPos;
    public float maxZPos;

    private bool needNewPosition = true;
    private bool isWalking = true;
    private Animator animator;
    private bool grounded = true;
    private Vector3 currentDestination;
    private Vector3 destination;
    private NavMeshAgent agent;
    NavMeshHit hit;

    // Use this for initialization
    void Start()
    {
        animator = GetComponentInChildren<Animator>();
        agent = GetComponent<NavMeshAgent>();

        MoveSheep();

        if (NavMesh.SamplePosition(destination, out hit, 1f, NavMesh.AllAreas))
        {
            destination = hit.position;
        }
    }

    void MoveSheep()
    {

        float xPos = transform.position.x + Random.Range(minXPos, maxXPos);
        float zPos = transform.position.z + Random.Range(minZPos, maxZPos);
        destination = new Vector3(xPos, 0, zPos);

        if (destination.x - transform.position.x < 5 && destination.z - transform.position.z < 5)
        {
            isWalking = false;
        }
        else
        {
            if (Vector3.Distance(destination, transform.position) > 1)
            {
                agent.destination = destination;
                isWalking = true;
                needNewPosition = false;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (followObject)
        {
            FollowAnObject();
        }
        else
        {
            if (agent.remainingDistance < 1)
            {
                MoveSheep();

                if (NavMesh.SamplePosition(destination, out hit, 1f, NavMesh.AllAreas))
                {
                    destination = hit.position;
                }
            }
        }
    }

    void FollowAnObject()
    {
        destination = new Vector3(followObject.transform.position.x, 0, followObject.transform.position.z);

        if (Vector3.Distance(destination, transform.position) > 1)
        {
            agent.destination = destination;
        }
    }
}
