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

public class MonsterManager : MonoBehaviour
{
    [SerializeField] private Monster _monsterPrefab = null;

    [SerializeField] private Vector2 _rightPosSpawn;
    [SerializeField] private Vector2 _leftPosSpawn;

    private int _monsterKilled = 0;

    private Coroutine _waveCoroutine = null;

    private WaveManager _waveManager = null;

    private List<Monster> _monsters = new List<Monster>();

    public int MonsterKilled { get => _monsterKilled; }

    public void Init(WaveManager waveManager)
    {
        _waveManager = waveManager;
        GameSceneManager.Instance.UiManager.GamePanel.DiplayEnemyKilled(_monsterKilled);
    }

    public void StartNewWave()
    {
        _waveCoroutine = StartCoroutine(SpawnWave());
    }

    public void OnMonsterKilled(Monster monster)
    {
        monster.OnKilled -= OnMonsterKilled;
        _monsters.Remove(monster);
        _monsterKilled++;
        GameSceneManager.Instance.UiManager.GamePanel.DiplayEnemyKilled(_monsterKilled);
        if (_monsters.Count <= 0)
        {
            _waveManager.NewWave();
        }
    }

    IEnumerator SpawnWave()
    {
        int enemyCount = (int)(_waveManager.WaveParameters.GetMonsterCount(_waveManager.WaveCount));
        UnityEngine.Debug.Log($"{ _waveManager.WaveCount} {enemyCount} enemy spawned");
        for (int i = 0; i < enemyCount; i++)
        {
            bool right = Random.value > 0.5f;
            Monster monster = Instantiate(_monsterPrefab, right ? _rightPosSpawn : _leftPosSpawn, Quaternion.identity, transform);
            monster.Initiliaze();
            monster.OnKilled += OnMonsterKilled;
            _monsters.Add(monster);
            yield return new WaitForSeconds(_waveManager.WaveParameters.GetDelayBetweenMonsters(_waveManager.WaveCount));
        }
        _waveManager.OnSpawnEnd();
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireCube(_rightPosSpawn, Vector2.one);
        Gizmos.DrawWireCube(_leftPosSpawn, Vector2.one);
    }
}
