using UnityEngine;
using UnityEngine.UI;

public class ToolTip : MonoBehaviour {
	public GameObject template; //must contain a Text child
	public string text;
	public float delay;

	private GameObject clone;
	private bool isOver = false;
	private float currentDelay;

	void Update() {

		if (isOver) {
			/*if (!button.interactable) {
				clone.SetActive(true);

				clone.transform.position = Input.mousePosition + new Vector3(5, -5, 0);
				clone.GetComponentInChildren<Text>().text = text;
			}
			else {
				clone.SetActive(false);
			}*/
			if (clone == null) {
				clone = GameObject.Instantiate(template, GameObject.Find("Canvas").transform);
			}

			currentDelay += Time.deltaTime;

			if (currentDelay >= delay && text != "") {
				clone.SetActive(true);

				clone.transform.position = Input.mousePosition + new Vector3(5, -5, 0);

				if (clone.transform.position.x + clone.GetComponent<RectTransform>().sizeDelta.x >= Screen.width) {
					clone.transform.position -= new Vector3(clone.GetComponent<RectTransform>().sizeDelta.x + 10, 0, 0);
				}
				if (clone.transform.position.y + clone.GetComponent<RectTransform>().sizeDelta.y >= Screen.height) {
					clone.transform.position += new Vector3(0, clone.GetComponent<RectTransform>().sizeDelta.y + 10, 0);
				}

				clone.GetComponentInChildren<Text>().text = text;
			}
			else {
				clone.SetActive(false);
			}
		}
	}

	public void mouseEnter() {
		isOver = true;
		currentDelay = 0.0f;
		if (clone != null) {
			Destroy(clone);
		}
		clone = GameObject.Instantiate(template, GameObject.Find("Canvas").transform);
	}

	public void mouseExit() {
		isOver = false;
		if (clone != null) {
			Destroy(clone);
		}
	}

	void OnDestroy() {
		if (clone != null) {
			Destroy(clone);
		}
	}
}
