using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody2D))]
public class TextController : MonoBehaviour {

    public float fadeTime = 0.5f;
    public Vector2 fadeVel = new Vector2(0.0f, 0.0f);
    public Color fadeCol = Color.white;

    public delegate void FadeAction();
    public event FadeAction FadeInAction;
    public event FadeAction FadeOutAction;

    private TextMesh textMesh;

    // Use this for initialization
    void Awake() {
        textMesh = GetComponent<TextMesh>();
        GetComponent<Rigidbody2D>().gravityScale = 0f;
    }

    public void FadeIn(string newText = null) {
        StartCoroutine(IFadeIn(newText));
    }

    public void FadeOut(bool destroy = true, bool fadeIn = false, string newText = null) {
        // Set the fade velocity
        textMesh.GetComponent<Rigidbody2D>().velocity = fadeVel;

        // Fade the mesh
        StartCoroutine(IFadeOut(destroy, fadeIn, newText));
    }

    private IEnumerator IFadeIn(string newText) {
        float time = 0f;
        Color color = textMesh.color;

        if (newText != null) textMesh.text = newText;

        // Fade the alpha value over time
        while (time < fadeTime) {
            float newAlpha = Mathf.Lerp(0, 1f, time / fadeTime);

            textMesh.color = new Color(color.r, color.g, color.b, newAlpha);

            time += Time.deltaTime;
            yield return null;
        }

        textMesh.color = new Color(color.r, color.g, color.b, 1f);
        if (FadeInAction != null) FadeInAction();
    }

    private IEnumerator IFadeOut(bool destroy, bool fadeIn, string newText) {
        float time = 0f;
        Color color = textMesh.color;

        // Fade the alpha value over time
        while (time < fadeTime) {
            Color newCol = Color.Lerp(color, fadeCol, time / fadeTime);
            float newAlpha = Mathf.Lerp(color.a, 0f, time / fadeTime);

            textMesh.color = new Color(newCol.r, newCol.g, newCol.b, newAlpha);

            time += Time.deltaTime;
            yield return null;
        }

        textMesh.color = new Color(fadeCol.r, fadeCol.g, fadeCol.b, 0f);
        if (FadeOutAction != null) FadeOutAction();

        if (fadeIn) StartCoroutine(IFadeIn(newText));
        else if (destroy) Object.Destroy(gameObject);
    }
}
