using System.Collections;
using UnityEngine;

public class CharacterSpawner : MonoBehaviour
{
    [SerializeField] private GameObject[] characters;
    [SerializeField] private GameObject gameCore;
    [SerializeField] private float time = 0.75f;
    private Timer timer;
    private float zPosition = -0.001f;
    private Transform parent;
    private bool startCharactersAreSpawned = false;
    public bool AreStartCharactersSpawned { get { return startCharactersAreSpawned; } }

    private void Awake()
    {
        parent = this.gameObject.transform;
    }

    private void Start()
    {
        timer = gameCore.GetComponent<Timer>();
    }

    private void Update()
    {
        DestroyCharacters();
    }

    private void SpawnOnStart()
    {
        Globals.Counter = 1;
        int charactersSpawnedOnStart = Random.Range(7, 12);
        for (int i = 0; i < charactersSpawnedOnStart; i++)
        {
            Vector3 spawnPosition = new Vector3(Random.Range(-3.2f, 3.2f), Random.Range(-5f, 7f), zPosition);
            zPosition -= 0.001f;
            GameObject gameObject = Instantiate(characters[Random.Range(0,characters.Length)], parent);
            gameObject.transform.localPosition = spawnPosition;
        }
    }

    private IEnumerator SpawnCharacter()
    {
        for (int i = 0; i < Random.Range(1, 4); i++)
        {
            Vector3 spawnPosition = new Vector3(Random.Range(-3.2f, 3.2f), 8, zPosition);
            zPosition -= 0.001f;
            GameObject gameObject = Instantiate(characters[Random.Range(0, characters.Length)], parent);
            gameObject.transform.localPosition = spawnPosition;
        }
        if (zPosition < -0.5f) zPosition = -0.001f;

        yield return new WaitForSeconds(time);
        if (timer.GetTime > 0) StartCoroutine(SpawnCharacter());
    } 

    private void DestroyCharacters()
    {

        if (timer.GetTime < 0)
        {
            var allChildren = this.GetComponentsInChildren<Transform>();

            foreach (Transform child in this.transform)
            {
                Destroy(child.gameObject);
            }
        }
    }

    public void StartGame()
    {
        SpawnOnStart();
        StartCoroutine(SpawnCharacter());
        startCharactersAreSpawned = true;
    }
}