using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BonusSpawner : MonoBehaviour
{
    #region Fields
    [SerializeField] private Bonus _bonus;
    [SerializeField] private Bonus _malus;
    [SerializeField] private Vector2 _minSpawnPos = Vector2.zero;
    [SerializeField] private Vector2 _maxSpawnPos = Vector2.zero;
    private WaveManager _waveManager = null;


    private float _waveTimer;
    private List<Bonus> _bonuses = new List<Bonus>();
    #endregion Fields

    #region Event
    #endregion Event

    #region Methods
    public void Init(WaveManager waveManager)
    {
        _waveManager = waveManager;
    }

    public void Update()
    {
        if (_waveManager == null)
        {
            return;
        }

        _waveTimer += Time.deltaTime;
        if (_bonuses.Count-1 < _waveManager.WaveParameters.GetMaxBonusOnScreen(_waveManager.WaveCount))
        {
            if (_waveTimer % _waveManager.WaveParameters.GetBonusSpawnRate(_waveManager.WaveCount) < Time.deltaTime)
            {
                Vector3 spawnPoint = new Vector2(Random.Range(_minSpawnPos.x, _maxSpawnPos.x), Random.Range(_minSpawnPos.y, _maxSpawnPos.y));
                spawnPoint.z = -5;
                Bonus bonus = Instantiate(Random.value > 0.5f ? _bonus : _malus, spawnPoint, Quaternion.identity, transform);
                _bonuses.Add(bonus);
                bonus.Init(_waveManager.WaveParameters.GetBonusSize(_waveManager.WaveCount));
                bonus.OnBonusCollected += OnBonusColledcted;
            }
        }
    }

    public void OnBonusColledcted(Bonus bonus)
    {
        bonus.OnBonusCollected -= OnBonusColledcted;
        _bonuses.Remove(bonus);
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.DrawCube((_maxSpawnPos + _minSpawnPos) / 2, _maxSpawnPos - _minSpawnPos);
    }
    #endregion Methods
}
