using System.Collections.Generic;
using System.Linq;
using Assets.Source.Patterns.ObjectPool;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Assets.Source.Core.Gameplay.Topdown
{
    public class AsteroidSpawner : MonoBehaviour
    {
        public float RespawnDelay = 5;
        public float SpawnRadius = 3;
        public float Chance = 1;
        private AsteroidTopdown _asteroid;

        private float _respawnDelayProgress;
        private bool _spawnDisabled;

        private List<Vector3> _positions;

        void Start()
        {
            if (GameManagerTopdown.Instance.WorldMap.Planets.Any(planet => planet.transform.position.DistTo(transform.position) < SpawnRadius + 4.5f))
            {
                _spawnDisabled = true;
                return;
            }
            if (GameManagerTopdown.Instance.WorldMap.Aliens.Any(alien => alien.transform.position.DistTo(transform.position) < SpawnRadius + 3))
            {
                _spawnDisabled = true;
                return;
            }
            if (Random.value > Chance)
                _spawnDisabled = true;
            _asteroid = SpawnAsteroid();
        }

        private AsteroidTopdown SpawnAsteroid()
        {
            if (_spawnDisabled)
                return null;
            var asteroid = Get.CommonPrefabs.TopdownPrefabs.Asteroids.GetRandom().Spawn(transform.position);
            asteroid.transform.position += new Vector3(Random.Range(-SpawnRadius, SpawnRadius),
                Random.Range(-SpawnRadius, SpawnRadius));
            asteroid.AddOnReleaseHandler(Respawn);
            return asteroid;
        }

        private void Respawn(IPoolObject poolObject)
        {
            _asteroid = null;
            _respawnDelayProgress = 0;
        }

        void FixedUpdate()
        {
            if (_spawnDisabled)
                return;
            _respawnDelayProgress += Time.fixedDeltaTime;
            var distToPlayer = GameManagerTopdown.Instance.Player.transform.position.DistTo(transform.position);
            if (_respawnDelayProgress > RespawnDelay && _asteroid == null && distToPlayer > 17)
            {
                _asteroid = SpawnAsteroid();
            }
        }

        void OnDrawGizmos()
        {
            Gizmos.color = Color.red.SetAlpha(0.33f);
            Gizmos.DrawWireSphere(transform.position, SpawnRadius);
        }
    }
}
