using UnityEngine;
using System.Collections;

public class Interact : MonoBehaviour {

	private bool interacted;

    private int heros = 0;

    [SerializeField]
    public string defaultTooltipText;

    public string tooltipText { get; set; }

    private float tooltipAlpha = 0.0f;

	[SerializeField]
	private int textSize = 32;

    [SerializeField]
    private float tooltipFadeSpeed = 2.0f;

    [SerializeField]
    private Vector3 tooltipOffset = new Vector3(0.0f, 0.5f, -2.0f);

	// Use this for initialization
	void Awake () {
        tooltipText = defaultTooltipText;
		if (textSize == null)
			textSize = 24;
	}

	public bool Interacted()
	{
		if (interacted)
		{
			interacted = false;

			return true;
		}

		return false;
	}

	void OnTriggerEnter(Collider other)
	{
		if (other.tag == "Hero")
		{
            ++heros;
		}
	}

	void OnTriggerExit(Collider other)
	{
		if (other.tag == "Hero")
		{
            --heros;
		}
	}

    void Update()
    {
        float targetTooltipAlpha = 0.0f;

        if (heros > 0)
        {
			Vector3 distToHero = FindObjectOfType<Hero>().transform.position - transform.position;
			if (distToHero.magnitude > 2) return;
			if (Input.GetKeyDown(KeyCode.Space) || Input.GetButtonDown("Fire1")) interacted = true;

            if (!string.IsNullOrEmpty(tooltipText))
            {
                tooltipAlpha = 1.0f;
                targetTooltipAlpha = 1.0f;
            }
        }
        else
        {
            targetTooltipAlpha = 0.0f;
        }

        tooltipAlpha = Mathf.MoveTowards(tooltipAlpha, targetTooltipAlpha, tooltipFadeSpeed * Time.deltaTime);
    }

    void OnGUI()
    {
        if (tooltipAlpha > 0.0f && !string.IsNullOrEmpty(tooltipText))
        {
            Vector3 pos = transform.position;
            pos += tooltipOffset;
            Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
            GUIStyle style = new GUIStyle(GUI.skin.label);
			style.fontSize = textSize;
            style.alignment = TextAnchor.MiddleCenter;
            GUI.Label(new Rect(screenPos.x - 100.0f, Screen.height - screenPos.y - 100.0f, 200.0f, 200.0f), tooltipText, style);
        }

    }
}
