using UnityEngine;
using System.Collections;

public class SpawnManager : MonoBehaviour {

    [System.Serializable]
    public class Wave
    {
        public GameObject Enemy;
        public int count = 10;
        public float spawnDelay = 0.2f;
    }

    public Wave[] waves;

    public Transform[] locations;

    public float waveDelay = 1f;
    public float growthRatio = 0.1f; // NOT IN USE


    int waveIndex = 0;
    float waveDelayCD = 1;
    float spawnDelayCD = 0;

    bool isEmpty = false;

    Transform _player;

	// Update is called once per frame
	void Update () {
        if (_player == null)
            _player = GameObject.FindGameObjectWithTag("Player").transform;

        if (isEmpty)
        {
            Enemy[] e = FindObjectsOfType<Enemy>();

            if (e.Length <= 0)
                FindObjectOfType<GameManager>().GameOver();
        }
        else {
            if (waveDelayCD <= 0) Spawn();
            else waveDelayCD -= Time.deltaTime;
        }
	}

    void Spawn()
    {
        if (waves[waveIndex].count > 0)
        {
            if (spawnDelayCD <= 0) PlaceEnemy();
            else spawnDelayCD -= Time.deltaTime;
        }
        else
        { 
            if (waveIndex < waves.Length-1) waveIndex++;
            else Empty();
        }
    }

    void Empty()
    {
        isEmpty = true;
    }

    void PlaceEnemy()
    {
        int loc = Random.Range(0, locations.Length - 1);
        GameObject enemy = (GameObject)Instantiate(waves[waveIndex].Enemy, locations[loc].transform.position, Quaternion.Euler(0, 0, Random.Range(0f, 360f)) );
        enemy.name = "Enemy";
        waves[waveIndex].count--;
        spawnDelayCD = waves[waveIndex].spawnDelay;
    }
}
