using UnityEngine;
using System.Collections.Generic;


public class BugSpawner : MonoBehaviour {
	public float SpawnRate = 5f;
	public int MaxBugs = 1;

	public GameObject BugPrefab;

	private bool recharging = true;
	private float rechargeStart = 0f;

	List<SpawnedBug> spawnedBugs = new List<SpawnedBug>();

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (recharging) {
			if((Time.time - rechargeStart) > SpawnRate) {
				SpawnBug ();
			}
		}
	}

	void RestartSpawner()
	{
		if (!recharging) {
			if (spawnedBugs.Count < MaxBugs) {
				recharging = true;
				rechargeStart = Time.time;
			} else {
				recharging = false;
			}
		}
	}

	void SpawnBug() {
		recharging = false;
		GameObject o = (GameObject)GameObject.Instantiate (BugPrefab, transform.position, Quaternion.identity);
		o.GetComponent<SpawnedBug> ().OwnerSpawner = this;
		spawnedBugs.Add (o.GetComponent<SpawnedBug> ());
		RestartSpawner();
	}

	public void BugRemoved(SpawnedBug bug)
	{
		if (spawnedBugs.Contains (bug)) {
			spawnedBugs.Remove (bug);
			RestartSpawner();
		}
	}
}
