// Status Readout class
// A class that positions and resizes a GUI text so that it appears to be 3D-positioned text.
//
// This is a very old class and it does a lot of things wrong.
using UnityEngine;
using System.Collections;

public class StatusReadout : MonoBehaviour 
{
	public Vector2 offset = new Vector2(0,0);
	public GUIText textComp;
	public GameObject textObject;
	public string text = "Test";
	public Color color = new Color(0,0,0,1);
	public bool setValues = false;
	public int size = 13;
	public float maxVisibilityDistance = 1000;
	public Falloff falloffRate = Falloff.Linear;
	public TextAlignment textAlignment = TextAlignment.Center;
	public FontStyle fontStyle = FontStyle.Normal;
	public TextAnchor textAnchor = TextAnchor.LowerCenter;
	
	//public float mod = 0;
	
	// Use this for initialization
	void Start() 
	{
		textObject = new GameObject( "GUI Text" );
		textObject.AddComponent<GUIText>();
		textObject.transform.parent = transform;
		textComp = textObject.GetComponent<GUIText>();
		textComp.material = textComp.font.material;
		textComp.alignment = textAlignment;
		textComp.fontStyle = fontStyle;
		textComp.anchor = textAnchor;
		SetText(text);
		SetColor(color);
		SetOffset(offset);
	}
	
	// Update is called once per frame
	void Update() 
	{
		if (textObject != null)
		{
			Vector3 objectPosition = Camera.main.WorldToViewportPoint(transform.transform.position);
			textObject.transform.position = objectPosition;
			
			float distance = Vector3.Distance(transform.position, Camera.main.transform.position);
			int modifiedSize = Mathf.Max(1,Mathf.RoundToInt(MathHelper.DoFalloff(falloffRate,distance,maxVisibilityDistance) * size));
			SetSize(modifiedSize);
		}
		if (setValues)
		{
			SetText(text);
			SetColor(color);
			SetOffset(offset);
			setValues = false;
		}
	}
	
	public void SetText(string textIn)
	{
		if (textComp != null)
		{
			textComp.text = textIn;
		}
	}
	public void SetSize(int sizeIn)
	{
		if (textComp != null)
		{
			textComp.fontSize = sizeIn;
		}
	}
	public void SetColor(Color color)
	{
		if (textComp != null)
		{
			textComp.material.color = color;
		}
	}
	public void SetOffset(Vector2 offset)
	{
		if (textComp != null)
		{
			textComp.pixelOffset = offset;
		}
	}
	public void Destroy()
	{
		if (textComp != null)
		{
			Component.Destroy(textComp);
			GameObject.Destroy(textObject);
			textObject = null;
			textComp = null;
		}
	}
	public void Create()
	{
		Destroy();
		Start();
	}
}