using System.Collections;
using UnityEngine;

[RequireComponent(typeof(NPC))]
public class AimAssistant : MonoBehaviour
{
    [HideInInspector] public GameObject enemy;
    private Shooting _shooting;
    public bool isFiring = false;
    private NPC _myNpc;
    [SerializeField] private float lookSpeed = 400f;
    private Transform _myTransform;
    private float _fireCountdown;

    //Я пытался придумать как обойти костыли с корутиной, но как видите ничего кроме других костылей не придумал.
    private bool _firelock = false;
    public bool fireAnimation = false;

    private void Awake()
    {
        _myNpc = GetComponent<NPC>();
        _shooting = GetComponent<Shooting>();
        _myTransform = transform;
        _fireCountdown = 1f / SettingsReader.Instance.GetSettings.RateOfFire;
    }

    private void FixedUpdate()
    {
        //Ищем противника на сцене.
        if (isFiring == false)
        {
            var enemies = GameManager.GetVisibleEnemies(_myNpc.GetCharacter.Team.GetOppositeTeam(), transform.position);
            if (enemies.Count == 0)
            {
                StopShooting();
                return;
            }
            else
            {
                enemy = enemies[new System.Random().Next(enemies.Count)];
                var character = enemy.GetComponent<ICharacter>();
                character.OnDeathEvent += _ =>
                {
                    isFiring = false;
                    _myNpc.AddReward(0.2f);
                };
                isFiring = true;
            }
        }
        else
        {
            if (Physics.Raycast(_myTransform.position, _myTransform.forward,
                    out var hit, SettingsReader.Instance.GetSettings.ViewDistance))
            {
                if (hit.collider.gameObject != enemy)
                {
                    StopCoroutine(nameof(Shooting));
                    StopShooting();
                    enemy = null;
                    return;
                }

                if (_firelock == false)
                {
                    fireAnimation = true;
                    StartCoroutine(nameof(Shooting));
                }
                _firelock = true;
            }
        }

        if (enemy != null)
        {
            var direction = enemy.transform.position - gameObject.transform.position;
            var targetRotation = Quaternion.LookRotation(direction);
            var lookAt = Quaternion.RotateTowards(gameObject.transform.rotation, targetRotation,
                Time.deltaTime * lookSpeed);
            lookAt.z = 0;
            lookAt.x = 0;
            gameObject.transform.rotation = lookAt;
        }
    }

    private void StopShooting()
    {
        _firelock = false;
        isFiring = false;
        fireAnimation = false;
    }

    private IEnumerator Shooting()
    {
        while (true)
        {
            _shooting.BotShoot();
            yield return new WaitForSeconds(_fireCountdown);
        }
    }
}