using System.Collections;
using UnityEngine;

namespace Shooter.Gameplay
{
    /// <summary>
    /// Стрелок: появляется, когда попадает в кадр, выходит вперёд на боевую позицию и
    /// затем периодически стреляет прицельными пулями по игроку, если тот в радиусе.
    /// </summary>
    public class Enemy_ShooterA : Enemy
    {
        [Header("Стрельба")]
        public GameObject m_BulletPrefab1;
        public GameObject m_FireParticlePrefab1;
        [Tooltip("Дистанция, на которой стрелок открывает огонь")]
        public float m_DetectionRange = 30f;

        bool m_Spawned = false;

        void Start()
        {
            m_FacePlayer = false;
        }

        void Update()
        {
            if (!m_Spawned &&
                CameraControl.m_Current.m_CameraTopPosition.z > transform.position.z &&
                transform.position.z >= CameraControl.m_Current.m_CameraBottomPosition.z)
            {
                m_Spawned = true;
                StartCoroutine(Co_EnterLevel());
            }

            HandleFacePlayer();
            HandleDeath();
        }

        IEnumerator Co_EnterLevel()
        {
            EnemyMovement movement = GetComponent<EnemyMovement>();
            movement.m_UsePhysics = false;
            movement.SetMoveTargetPosition(transform.position + m_StartWalkDistance * transform.forward);
            m_FacePlayer = false;
            while (!movement.m_ReachedTargetPosition)
                yield return null;

            StartCoroutine(Co_AttackLoop());
        }

        IEnumerator Co_AttackLoop()
        {
            m_FacePlayer = true;
            while (true)
            {
                yield return new WaitForSeconds(.1f);
                if (Vector3.Distance(transform.position, PlayerChar.m_Current.transform.position) <= m_DetectionRange)
                    ShootBullet();
                yield return new WaitForSeconds(1.5f);
            }
        }

        public void ShootBullet()
        {
            GameObject obj = Instantiate(m_BulletPrefab1);
            obj.transform.position = m_FirePoint.position;
            Vector3 dir = PlayerChar.m_Current.transform.position - transform.position;
            dir.y = 0;
            obj.transform.forward = dir;
            obj.GetComponent<ProjectileCollision>().m_Creator = gameObject;
            Destroy(obj, 10);

            obj = Instantiate(m_FireParticlePrefab1);
            obj.transform.position = m_FirePoint.position;
            Destroy(obj, 3);
        }

        void OnDrawGizmos()
        {
            Gizmos.DrawLine(transform.position, transform.position + m_StartWalkDistance * transform.forward);
        }
    }
}
