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

[CreateAssetMenu(fileName = "PatrolDecision", menuName = "RiftMayhem/AI/Decisions/Patrol")]
public class NPCPatrolDecision : NPCDecision
{
    [Header("Settings:")]
    [SerializeField] private float distanceToChangePatrolDestination;
    [SerializeField] private float patrolAgentSpeed;

    NavMeshAgent agent;
    Vector3 patrolDestination = new Vector3();

    public UnityEvent OnPatrolReachedDestination = new UnityEvent();


    public override IEnumerator ExecuteCoroutine(NPCBrain npc)
    {
        SetupAgent(npc);

        StartPatrollingToNewPosition();

        yield return new WaitUntil(() => IsPathComplete());

        OnPatrolReachedDestination.Invoke();
    }

    public override void Interrupt(NPCBrain npc)
    {
        if (executeRoutine != null)
            npc.StopCoroutine(executeRoutine);
    }



    //Helpers
    protected void StartPatrollingToNewPosition()
    {
        agent.speed = patrolAgentSpeed;

        patrolDestination.x = Random.Range(-5, 5);
        patrolDestination.y = 0f;
        patrolDestination.z = Random.Range(-5, 5);

        agent.SetDestination(agent.transform.position + patrolDestination);
        agent.isStopped = false;
    }

    protected bool IsPathComplete()
    {
        if (Vector3.Distance(agent.destination, agent.transform.position) <= agent.stoppingDistance)
        {
            if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
            {
                return true;
            }
        }
        return false;
    }

    protected void SetupAgent(NPCBrain npc)
    {
        agent = npc.Agent;
    }

    public override bool IsPossibleToExecute(NPCBrain npc)
    {
        return !npc.IsDead() && !npc.IsCasting();
    }
}
