﻿using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {
	public GameObject[] attackerPrefabArray;
	public float spawnDelay= 15f;

	private float timeSinceLastSpawned = 0f;

	// Update is called once per frame
	void Update () {
		foreach (GameObject thisAttacker in attackerPrefabArray) {
			if (IsTimeToSpawn(thisAttacker)){
				Spawn(thisAttacker);
				//display what was spawned for play tuning:
				print (thisAttacker);
			}
		}
		timeSinceLastSpawned += Time.deltaTime;
	}

	void Spawn (GameObject gameObject){
		GameObject myAttacker = Instantiate (gameObject) as GameObject;
		myAttacker.transform.parent = transform;
		myAttacker.transform.position = transform.position;
		timeSinceLastSpawned = 0f;
	}

	bool IsTimeToSpawn(GameObject myAttacker){
		if (Time.timeSinceLevelLoad < spawnDelay) {
			return false;
		}
		Attacker attacker = myAttacker.GetComponent<Attacker>();
		float meanSpawnDelay = attacker.seenEverySeconds;
		float spawnsPerSecond = 1f / meanSpawnDelay;
		//check to see if it's too fast.
		if (Time.deltaTime > meanSpawnDelay) {
			Debug.LogWarning ("Spawn rate capped by frame rate");
		}
		bool stillPrego = QuietBeforeTheStorm (meanSpawnDelay);
		float threshold = spawnsPerSecond * Time.deltaTime;
		bool imReady = ((5f * Random.value < 5f * threshold) && !stillPrego);

		return imReady;
	}

	bool QuietBeforeTheStorm (float meanSpawnDelay)	{
		//Calculate how long it's been since the last spawn, if too early wait
		bool stillPrego = (timeSinceLastSpawned < meanSpawnDelay);
		return stillPrego;
	}
}
