using UnityEngine;
using System.Collections;

public class EnemySpawner : MonoBehaviour 
{
	public Object[] enemyPrefab;

	public float NextSpawn = 0.0f;

	public const float SPAWN_RATE_MIN = 2.0f;
	public const float SPAWN_RATE_MAX = 8.0f;

	public bool Active = false;
	BuildController buildController;

	public float SpawnAdjust;
	float spawnAdjustTotal;

	void Awake()
	{
		buildController = FindObjectOfType<BuildController>();
	}

	void Update()
	{
		if(!Active && !buildController.Building)
		{
			Active = true;
			StartCoroutine (SpawnEnemy ());
		}
	}

	private IEnumerator SpawnEnemy ()
	{
		NextSpawn = Random.Range (SPAWN_RATE_MIN, SPAWN_RATE_MAX);
		NextSpawn -= spawnAdjustTotal;
		spawnAdjustTotal -= SpawnAdjust;
		if(NextSpawn < SPAWN_RATE_MIN)
			NextSpawn = SPAWN_RATE_MIN;
		int randomPrefab = Random.Range (0, enemyPrefab.Length);

		GameObject newEnemy = (GameObject) Instantiate (enemyPrefab[randomPrefab], transform.position + new Vector3 (Random.Range(-20, 20), 0, 0), Quaternion.identity);
		newEnemy.transform.SetParent(transform);
		yield return new WaitForSeconds (NextSpawn);
		StartCoroutine(SpawnEnemy() );
	}
}
