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

public class EnemyController : MonoBehaviour
{

    public Transform[] patrolPoints;
    public int currentPatrolPoint;

    public NavMeshAgent agent;

    public Animator anim;

    public enum AIState
    {
        isIdle, isPatrolling, isChasing
    };

    public AIState currentState;

    public float waitAtPoint = 2f;
    private float waitCounter;

    public float chaseRange;

    // Start is called before the first frame update
    void Start()
    {
        waitCounter = waitAtPoint;
    }

    // Update is called once per frame
    void Update()
    {
        float distanceToPlayer = Vector3.Distance(transform.position, PlayerController.instance.transform.position);

        switch(currentState)
        {
            case AIState.isIdle:

            anim.SetBool("IsMoving", false);

            if(waitCounter > 0)
            {
                waitCounter -= Time.deltaTime;
            } 
            
            else
            {
                currentState = AIState.isPatrolling;
                agent.SetDestination(patrolPoints[currentPatrolPoint].position);
            }

            if(distanceToPlayer <= chaseRange)
            {
                currentState = AIState.isChasing;
                anim.SetBool("IsMoving", true);
            }
            
            break;

            case AIState.isPatrolling:
            

         //agent.SetDestination(patrolPoints[currentPatrolPoint].position);

        if(agent.remainingDistance <= .2f)
        {
            currentPatrolPoint++;
            if(currentPatrolPoint >= patrolPoints.Length)
            {
                currentPatrolPoint = 0;
            }

            //agent.SetDestination(patrolPoints[currentPatrolPoint].position);

            currentState = AIState.isIdle;
            waitCounter = waitAtPoint;

;
        }

                    if(distanceToPlayer <= chaseRange)
            {
                currentState = AIState.isChasing;
            }

        anim.SetBool("IsMoving", true);

        break;

        case AIState.isChasing:

        agent.SetDestination(PlayerController.instance.transform.position);

        break;

        }

    }
}
