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

public class Follower : MonoBehaviour {

	private static List<Follower> followerInstances = new List<Follower> ();
	public static Follower[] followers
	{
		get
		{
			return followerInstances.ToArray();
		}
	}

	public GameObject target;
	public Vector3 offset;
	public bool lookAt;
	public bool follow;
	public float followSpeed;
	public float lookSpeed;
	public bool lookatVelocity;
	public Rigidbody targetRigidbody;

	void Awake()
	{
		followerInstances.Add (this);
	}

	void OnDestroy()
	{
		followerInstances.Remove (this);
	}

	// Update is called once per frame
	void FixedUpdate () {
		if (!target) {
			return;
		}

		if (follow) {
			transform.position = Vector3.Lerp (transform.position, target.transform.position + offset, Time.fixedDeltaTime * followSpeed);
		}
		if (lookAt) {
			if (lookatVelocity && targetRigidbody)
			{
				transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation ((target.transform.position - transform.position) + targetRigidbody.velocity, transform.parent.forward), Time.fixedDeltaTime * lookSpeed);
			}
			else 
			{
				if (transform.parent)
				{
					transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation ((target.transform.position - transform.position), transform.parent.forward), Time.fixedDeltaTime * lookSpeed);
				}
				else
				{
					transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation ((target.transform.position - transform.position), Vector3.up), Time.fixedDeltaTime * lookSpeed);
				}
			}
		}
	}
}
