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

public class WaveManager : MonoBehaviour
{
    [Header("General")]
    [SerializeField] private List<Wave> waves = new List<Wave>();
    [Space]
    [SerializeField] private Transform[] spawnPoints;

    [HideInInspector] public List<GameObject> curEnemies = new List<GameObject>();

    [Header("Boss")]
    [SerializeField] private GameObject boss;
    [SerializeField] private Transform bossSpawnPoint;

    [Header("Other")]
    private int waveNumber;
    private bool waveActive;
    private bool bossWave;


    void Update()
    {
        if (waveActive == true)
        {
            if (curEnemies.Count == 0)
            {
                if (bossWave == false)
                {
                    waveActive = false;
                    EndWave();
                }
                else if (bossWave == true)
                {
                    Game.game.ui.StartCoroutine(Game.game.ui.OutroScreen());
                }
            }
        }
    }

    // Следующая волна
    public void NextWave()
    {
        curEnemies.Clear();

        StartCoroutine(Spawn());
    }

    public void EndWave()
    {
        Game.game.player.AddMoney(waves[waveNumber].reward);
        Game.game.map.BlockWays(false);
    }

    // Спавн врагов в рандомных позициях
    IEnumerator Spawn()
    {
        if (Game.game.difficult < 2)
        {
            waveNumber = Random.Range(0, 5);
        }
        else if (Game.game.difficult >= 2 && Game.game.difficult < 3)
        {
            waveNumber = Random.Range(5, 10);
        }
        else if (Game.game.difficult >= 3)
        {
            waveNumber = Random.Range(10, 15);
        }

        for (int x = 0; x < waves[waveNumber].enemy.Length; x++)
        {
            for (int i = 0; i < waves[waveNumber].spawnCount[x]; i++)
            {
                yield return new WaitForSeconds(waves[waveNumber].spawnRates[x]);

                int spawnPosNumber = Random.Range(0, spawnPoints.Length);
                GameObject enemy = Instantiate(waves[waveNumber].enemy[x], spawnPoints[spawnPosNumber].position, spawnPoints[spawnPosNumber].rotation);

                enemy.GetComponent<Enemy>().SetTarget();
                curEnemies.Add(enemy);
            }
        }

        waveActive = true;
    }

    // Спавн босса
    public void SpawnBoss()
    {
        bossWave = true;

        GameObject enemy = Instantiate(boss, bossSpawnPoint.position, bossSpawnPoint.rotation);
        enemy.GetComponent<Enemy>().SetTarget();

        curEnemies.Add(enemy);

        waveActive = true;

        print("Spawn boss!");
    }
}
