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

public class Roam : NPCBase
{

    // could also define an area to roam in rather than set waypoints
    GameObject[] waypoints;
    int currentWaypoint = 0;
    float lastTime;

    void Awake()
    {
        waypoints = GameObject.FindGameObjectsWithTag("waypoint");
        Debug.Log("Found " + waypoints.Length + " waypoints!" );
    }
    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        base.OnStateEnter(animator, stateInfo, layerIndex);
        
        if(!npcNav.hasPath)
            SetNewGoal(npcNav);

        npcNav.isStopped = false;
        lastTime = Time.time;

        brain.SetRoamObject(true);
    }

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (waypoints.Length == 0) return;
        if (npcNav.remainingDistance < 2f)
            SetNewGoal(npcNav);


        // while moving we're losing energy
        if(Time.time > lastTime + 1f)
        {
            brain.LoseEnergy();
            lastTime = Time.time;
        }
    }

    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        brain.SetRoamObject(false);
    }

    void SetNewGoal(NavMeshAgent agent)
    {
        // skip if there aren't any goals
        if (waypoints.Length == 0)
            return;

        // set random waypoint
        var goal = waypoints[Random.Range(0, waypoints.Length)];

        agent.SetDestination(goal.transform.position);
    }
}
