using UnityEngine;
using System.Collections;

public class LollipopController : MonoBehaviour
{
		private Queue lollipops;
		public GameObject prefab;
	
		private const float SPAWN_INTERVAL = 3.0f;
		private const int N_VISIBLE = 8;
		private float previousSpawn;
		private bool _enabled;

		void Start ()
		{
				lollipops = new Queue ();
		}
	
		public void SetEnabled (bool enabled)
		{
				foreach (var l in lollipops)
						((GameObject)l).SetActive (enabled);
						
				_enabled = enabled;
		}
	
		void Update ()
		{
				if ((Time.time - previousSpawn) < SPAWN_INTERVAL)
						return;
				previousSpawn = Time.time;

				GameObject go;
				if (lollipops.Count < N_VISIBLE) {
						go = (GameObject)(GameObject.Instantiate (prefab));
						go.SetActive (_enabled);
				} else {
						go = (GameObject)lollipops.Dequeue ();
				}
			
				float angle, magnitude;
				angle = UnityEngine.Random.value * 360.0f;
				magnitude = 20.0f + 20.0f * UnityEngine.Random.value;
			
				Vector2 direction = new Vector2 (magnitude * Mathf.Cos (angle), magnitude * Mathf.Sin (angle));
				Vector3 position = transform.position + new Vector3 (direction.x, 0, direction.y);
				position.y = Terrain.activeTerrain.SampleHeight (position);

				go.transform.position = position;
				lollipops.Enqueue (go);
		}
}
