using System;
using Sources.Enemies;
using UniRx;
using UnityEngine;
using Zenject;
using Random = UnityEngine.Random;

public class Spawner : MonoBehaviour
{
    [SerializeField] private AggrableEnemy _enemyToSpawn;
    [SerializeField] private float _radius;
    [SerializeField] private float _cooldown = 20f;
    [SerializeField] private int _amount = 1;

    [Inject] private DiContainer _container;
    
    private bool _isOnCoolDown;
    private int _liveEnemiesCount;
    
    private void Update()
    {
        if (_liveEnemiesCount >= _amount)
            return;
        
        if (_isOnCoolDown)
            return;
        
        var pos = transform.position + (Vector3)Random.insideUnitCircle * _radius;
        var newEnemy = _container.InstantiatePrefabForComponent<AggrableEnemy>(
            _enemyToSpawn, pos, Quaternion.identity, transform.parent);
         
        _liveEnemiesCount++;

        newEnemy.OnDied += OnEnemyDied;
    }

    private void OnEnemyDied(AggrableEnemy enemy)
    {
        _liveEnemiesCount--;
        enemy.OnDied -= OnEnemyDied;
        
        _isOnCoolDown = true;
        Observable.Timer(TimeSpan.FromSeconds(_cooldown)).Subscribe(_ => _isOnCoolDown = false);
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, _radius);
    }
}