using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    [SerializeField]
    private Text _killText, _gameOverText;
    [SerializeField]
    private int killsToLightsEffect, killsToSpeedEffect;
    public GameObject lightsContainer;
    public Transform spawnersContainer;


    private int _kills = 0;
    private bool _listeningForRestartInput = false;

    bool _startedLightsEffect = false;
    bool _startedSuperZombiesEffect = false;

    private void Start() {
        _listeningForRestartInput = false;
        _gameOverText.gameObject.SetActive(false);
    }

    private void Update() {
        if (_listeningForRestartInput) {
            if (Input.GetKeyDown(KeyCode.Space)) {
                SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
            }
        }
    }

    public void IncrementKillCounter() {
        _kills++;
        _killText.text = "kills: " + _kills;
        if (!_startedLightsEffect && _kills > killsToLightsEffect) {
            _startedLightsEffect = true;
            StartCoroutine(LightsEffect());
        }
        if (!_startedSuperZombiesEffect && _kills > killsToSpeedEffect) {
            _startedSuperZombiesEffect = true;
            SuperZombiesEffect();
        }
    }

    public IEnumerator LightsEffect() {
        for (int i = 0; i < 10; i++) {
            // Lights start to flicker here
            yield return new WaitForSeconds(2f);
            lightsContainer.SetActive(false);
            yield return new WaitForSeconds(0.3f);
            lightsContainer.SetActive(true);
        }
        // Lights die
        lightsContainer.SetActive(false);
    }

    public void SuperZombiesEffect() {
        // todo change music here
        foreach (Transform child in spawnersContainer) {
            EnemySpawner spawner = child.GetComponent<EnemySpawner>();
            if (spawner) {
                spawner.SetDoubleZombieSpeed();
            }
        }
    }

    public void GameOver() {
        _gameOverText.gameObject.SetActive(true);
        _listeningForRestartInput = true;
    }
}
