using AsteroidGame.ScriptableObjects;
using UnityEngine;
using UnityEngine.AI;

namespace AsteroidGame.Entities
{
    public class EnemyBase : EntityBase
    {
        [SerializeField] private SoEntityBaseRuntimeSet _enemyBaseSet;

        [field: Header("Targeter")]
        [field: SerializeField] public Targeter Targeter { get; set; }

        [field: Header("NavMeshAgent")]
        [SerializeField] private NavMeshAgent _navMeshAgent;

        protected override void OnEnable()
        {
            base.OnEnable();

            _enemyBaseSet.Add(this);

            InitializeTargeter();

            InitializeNavMeshAgent();
        }

        private void InitializeTargeter()
        {
            if (Targeter != null)
            {
                Targeter = gameObject.GetComponentInChildren<Targeter>();
            }

            Targeter.SetParent(Targetable);
        }

        private void InitializeNavMeshAgent()
        {
            if (_navMeshAgent != null)
            {
                _navMeshAgent = gameObject.GetComponentInChildren<NavMeshAgent>();
            }

            _navMeshAgent.speed = 0.1f;
        }

        protected override void OnDisable()
        {
            base.OnDisable();
            _enemyBaseSet.Remove(this);
        }

        private void Update()
        {
            if (!Targeter.FoundTarget()) return;

            Targetable = Targeter.GetTarget();
            _navMeshAgent.SetDestination(Targetable.GetBasePosition());
        }
    }
}