using UnityEngine;
using System.Collections;
using System.Collections.Generic;

// The Infinity Manager helps to keep precision errors to a minimum.
// It does this by watching an object, the 'benchmark.' The benchmark should always be kept within a certain distance from the world origin (0,0,0)
// If the benchmark exceeds the max distance, the benchmark and a list of objects will be offset.
// The offset will place the benchmark at the origin.
public class InfinityManager : MonoBehaviour {

	public Transform benchmark;
	public Transform[] initialObjects;

	public float maxDistance = 1000;

	private static List<Transform> objects;

	public Transform[] objects_inspect;

	void Awake()
	{
		objects = new List<Transform> (initialObjects);
	}

	void LateUpdate () 
	{
		if (benchmark && (Mathf.Abs(benchmark.position.y) > (maxDistance))) {
			float offset = benchmark.position.y;
			benchmark.position = new Vector3(benchmark.position.x, 0, benchmark.position.z);

			bool houseCleaning = false;

			foreach (Transform t in objects)
			{
				if (t)
				{
					t.position =  new Vector3(t.position.x, t.position.y - offset, t.position.z);
				}
				else
					houseCleaning = true;
			}

			if (houseCleaning)
			{

				objects.RemoveAll(IsNull);
			}
		}

		objects_inspect = objects.ToArray ();
	}

	public static void Add(Transform t)
	{
		// I guess we're allowed to 
		if (objects == null) {
			objects = new List<Transform>();
		}
		objects.Add (t);
	}

	public static void Remove (Transform t)
	{
		if (objects != null)
			objects.Remove (t);
	}

	// Yup.
	// Is there a built-in null checking static bool function that equates an object to null?
	// Who cares.
	private static bool IsNull(Object o)
	{
		return o == null;
	}
}
