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

public class SpawnManager : MonoBehaviour
{
    public GameObject[] spawningEnemies;
    public Transform[] spawnPoints;
    public GameObject[] landingPoints;
    public bool running = true;
    public Animator animator;

    float elapsedTime;
    private int lastSpawn = -1;

    [SerializeField]
    private int worldSeed = 1111;

    [SerializeField]
    private int countEnemies;

    [SerializeField]
    private GameObject EnemyAlert;

    void OnEnable()
    {
        Random.InitState(worldSeed);
    }

    // Start is called before the first frame update
    void Start()
    {
        //Eventually put timer in game manager
        StartCoroutine("SpawnNewEnemy");
    }

    private void Update()
    {
        elapsedTime += Time.deltaTime;
    }


    IEnumerator SpawnNewEnemy()
    {
        while (running)
        {
            GameObject spawned = Instantiate(GetRandomEnemy(), GetRandomSpawn().transform.position, Quaternion.identity);

            foreach (Transform trans in spawned.GetComponentsInChildren<Transform>(true))
            {
                trans.gameObject.layer = gameObject.layer;
            }

            spawned.layer = gameObject.layer;
            spawned.GetComponent<Enemy>().SetLandingPoint(GetRandomLandingPoint().transform);
            countEnemies++;
            animator.SetInteger("Enemies", countEnemies);
            //TODO: replace 2f by function depending on elapsed time, decreasing waiting time over time
            yield return new WaitForSeconds(2f);
        }
        
    }

    GameObject GetRandomEnemy()
    {
        int index = Random.Range(0, spawningEnemies.Length);
        return spawningEnemies[index];
    }

    GameObject GetRandomLandingPoint()
    {
        int index = Random.Range(0, landingPoints.Length);
        return landingPoints[index];
    }

    /**
     * Get a random spawn point in array.
     * You can't get the same spawn point twice
     */
    Transform GetRandomSpawn()
    {
        int index = Random.Range(0, spawnPoints.Length);
        if (lastSpawn != -1)
        {
            while (index == lastSpawn)
            {
                index = Random.Range(0, spawnPoints.Length);
            }
        }

        lastSpawn = index;

        return spawnPoints[index];
    }

}
