using ftt.Core.Managing;
using UnityEngine;
using UnityEngine.AI;

namespace ftt.Gameplay.AI
{
    public class MinotaurEntity : MonoBehaviour
    {
        [Header("Set in inspector")]
        [SerializeField] float movementSpeed;
        [SerializeField] Transform[] patrolPoints;
        [SerializeField] float idleTimeOnPatrol;
        [SerializeField] float refreshTimeAfterChase;
        [SerializeField] float pointDistanceOffset;
        [SerializeField] Transform target;
        [SerializeField] float minimumDistanceToCatch;

        [Header("Occlusion check layers")]
        public LayerMask occlusionLayers;

        NavMeshAgent agent;
        MinotaurNodeData nodeData;
        MinotaurBTHandler btHandler;
        EntityAttackFOV attackFOV;

        private void Awake()
        {
            agent = GetComponent<NavMeshAgent>();
            attackFOV = GetComponentInChildren<EntityAttackFOV>();

            nodeData = CreateNodeData();

            //Creates the bt handler
            btHandler = new MinotaurBTHandler(this, nodeData);
        }

        MinotaurNodeData CreateNodeData()
        {
            MinotaurNodeData data = new MinotaurNodeData(this);

            data.SetMovementSpeed(movementSpeed);
            data.SetPatrolPoints(patrolPoints);
            data.SetNavMeshAgent(agent);
            data.SetCurrentWaypointIndex(0);
            //data.SetIdleTimeOnPatrol(idleTimeOnPatrol);
            data.SetOcclusionLayers(occlusionLayers);
            data.SetPointDistanceOffset(pointDistanceOffset);
            data.SetTarget(GameManager.GetManager.Player.transform);
            data.SetTargetFound(false);
            data.SetRefreshPatrolTime(refreshTimeAfterChase);
            data.SetMinimumDistanceToCatch(minimumDistanceToCatch);

            return data;
        }

        private void Update()
        {
            if (btHandler != null)
            {
                btHandler.UpdateBehaviour();
            }
        }

        public void SetTargetFound()
        {
            bool result = attackFOV.IsTargetInsideFrustrum();
            nodeData.SetTargetFound(result);
        }

        public Transform GetTarget => target;
    }
}