using UnityEngine;
using System.Collections;

//
// надписи в интерфейсе
//
[ExecuteInEditMode]
[RequireComponent (typeof (MeshRenderer))]
[RequireComponent (typeof (TextMesh))]
public class Label : MonoBehaviour {
	
	[SerializeField] string textValue = "";
	[SerializeField] Font  font = null;			
	[SerializeField] Color color = new Color(0, 0, 0, 1);
	[SerializeField] float size = 0.5f;
	
	TextMesh labelMesh;											// создаваемые объекты
	MeshRenderer meshRenderer;
	
	private bool visibility = true;
	
	public bool visible {
        get {
            return visibility;
        }
        set {
			if (visibility != value) {
				SetVisible(value);
			}
        }
    }
	
	public string text {
        get {
            return textValue;
        }
        set {
			if (textValue != value)	{
				SetText(value);
			}
        }
    }
	// установть видимость
	private void SetVisible(bool val){
		if(visibility != val){
			visibility = val;		
			meshRenderer.enabled = val;
		}
	}
	
	// добавить объект текста
	public static Label Create(Transform parent, Vector3 position, string text, float size, Font font) {
		GameObject labelObject = new GameObject();
		labelObject.name = "label";
		labelObject.transform.parent = parent;
		labelObject.transform.localPosition = position;
		
		Label label = labelObject.AddComponent<Label>() as Label;
		label.font = font;
		label.SetSize(size);
		label.SetText(text);
		return label;
	}
	
	void Awake(){
		labelMesh = gameObject.GetComponent<TextMesh>();
		if (labelMesh == null) {
			labelMesh = gameObject.AddComponent<TextMesh>() as TextMesh;
			if (font == null)
				font = Resources.Load("Font/Helvetica_LT") as Font;		// euro
			labelMesh.font = font;
			labelMesh.anchor = TextAnchor.MiddleCenter;
		}
		labelMesh.text = textValue;
		labelMesh.characterSize = size;
		
		meshRenderer = gameObject.GetComponent<MeshRenderer>();
		if (meshRenderer == null){
			meshRenderer = gameObject.AddComponent<MeshRenderer>() as MeshRenderer;
			meshRenderer.material = labelMesh.font.material;
			meshRenderer.material.color = color;
		}
	}
	
	public void SetSize(float labelSize){
		size = labelSize;
		labelMesh.characterSize = size * (32.0f/50.0f);
	}
	
	public void SetAnchor(TextAnchor anchor){
		labelMesh.anchor = anchor;
	}
	
	// установить текст
	public void SetText(string txt){
		textValue = txt;
		labelMesh.text = textValue;
	}
	
	// задать цвет
	public void SetColor(Color color){
		labelMesh.renderer.material.color = color;
	}
}
