using UnityEngine;
using System.Collections;

public class SpawnController : MonoBehaviour
{
		private float previousSpawn;
		private const float SPAWN_INTERVAL = 3.0f;
		private System.Collections.Queue lastVisited;

		void Start ()
		{
				lastVisited = new System.Collections.Queue ();
				
				var allSpawnPoints = GameObject.FindGameObjectsWithTag ("SpawnPoint");
				foreach (var sp in allSpawnPoints) {
						sp.transform.position = new Vector3 (sp.transform.position.x,
						Terrain.activeTerrain.SampleHeight (sp.transform.position), sp.transform.position.z);
				}
				
				var allAnimals = GameObject.FindGameObjectsWithTag ("Animal");
				foreach (var a in allAnimals) {
						a.transform.position = new Vector3 (a.transform.position.x,
			                                     Terrain.activeTerrain.SampleHeight (a.transform.position) + 2f, a.transform.position.z);
				}
		}

		private Player getPlayer ()
		{
				return gameObject.GetComponent ("Player") as Player;
		}

		public void SpawnPointVisited (SpawnPoint sp)
		{
				lastVisited.Enqueue (sp);
				
				if (lastVisited.Count > 3)
						lastVisited.Dequeue ();
		}

		public void PlayerStateChanged (Player pl)
		{
				var spawnPointGos = GameObject.FindGameObjectsWithTag ("SpawnPoint");

				foreach (var go in spawnPointGos) {
						var sp = (SpawnPoint)go.GetComponent ("SpawnPoint");
						sp.StateChanged (pl);
				}
		}

		void Update ()
		{
				if ((Time.time - previousSpawn) < SPAWN_INTERVAL)
						return;
				previousSpawn = Time.time;
		
				var colliders = Physics.OverlapSphere (transform.position, 200.0f);

				Collider nearestCollider = null;
				float distance = Mathf.Infinity;
				for (var i = 1; i < colliders.Length; i++) {
						if (colliders [i].gameObject.tag != "SpawnPoint")
								continue;
				
						float d = (colliders [i].transform.position - transform.position).magnitude;
						
						if (d < distance) {
								distance = d;
								nearestCollider = colliders [i];
						}
				}
				
				foreach (var c in colliders) {
						if (c == nearestCollider)
								continue;
				
						var go = c.gameObject;
						
						if (go.tag == "SpawnPoint") {
								SpawnPoint sp = go.GetComponent ("SpawnPoint") as SpawnPoint;
								
								if (!lastVisited.Contains (sp))
										sp.Spawn (getPlayer ());
						}
				}
		}
}
