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

namespace AsteroidGame.Entities
{
    public class EnemyBase : EntityBase
    {
        [field: Header("Weapon")]
        [field: SerializeField] public List<Weapon> Weapons { get; set; }

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

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

        protected void OnEnable()
        {
            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;
        }

        private void Update()
        {
            if (Targeter.FoundTarget())
            {
                foreach (var weapon in Weapons)
                {
                    weapon.PivotPoint.transform.LookAt(Targeter.GetTarget().GetCenterPosition());
                    weapon.FireWeapon = true;
                }

                Targetable = Targeter.GetTarget();
                _navMeshAgent.SetDestination(Targetable.GetBasePosition());
            }
            else
            {
                foreach (var weapon in Weapons)
                {
                    weapon.FireWeapon = false;
                }
            }
        }
    }
}