namespace Grunt_gun
{

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


    public class PatrolState : BaseState
    {
        private bool playerDetected;
        
        public Enemy_1 enemy;
        public Path path;
        public int waypointIndex;
        public Enemy_1 Gun { get { return enemy; } }

        public PatrolState(Path path, Enemy_1 enemy)
        {
            this.path = path;
            this.enemy = enemy;

            //Debug.Log("Enemy_1 initialized: " + (enemy1 != null));
        }

        public PatrolState(Path path)
        {
            this.path = path;
        }

        public Vector3 GetNextWaypoint()
        {
            if (waypointIndex < path.waypoints.Count)
            {
                Vector3 nextWaypointPosition = path.waypoints[waypointIndex].position;
                return nextWaypointPosition;
            }
            else
            {
                Debug.LogWarning("No waypoints");
                return Vector3.zero;
            }
        }      

        public override void Enter()

        {


        }

        public override void Perform()

        {
            Debug.Log("PatrolState Perform() method executed");
            if (enemy != null)
            {
                PatrolCycle();
                // Check if the player is detected by this enemy
                if (enemy.CanSeePlayer())
                {
                    Debug.Log("Player detected in PatrolState. Transitioning to AttackState.");
                    stateMachine.ChangeGunState(new AttackState(enemy));// Change the current state to AttackState, passing the enemy object
                    Debug.Log("Player is currently detected");                   
                }      
                else
                {
                   Debug.Log("player no longer detected");
                }
            }
        }

        public void UpdatePlayerDetected(bool detected)
        {
            playerDetected = detected;
        }

        public override void Exit()

        {
            if (Gun.Agent.remainingDistance < 0.2f)
            {
                if (waypointIndex < Gun.path.waypoints.Count - 1)
                    waypointIndex++;
                else
                    waypointIndex = 0;

                Gun.Agent.SetDestination(Gun.Path.waypoints[waypointIndex].position);

            }
        }


        public void PatrolCycle()

        {
            if (Gun.Agent.remainingDistance < 0.2f && !Gun.Agent.pathPending)
            {
                waypointIndex++;

                if (waypointIndex >= path.waypoints.Count)
                {
                    waypointIndex = 0;
                }

                Gun.Agent.SetDestination(path.waypoints[waypointIndex].position);
            }
        }


    }
}