using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(TextMeshProUGUI))]
public class TypingText : MonoBehaviour
{
    public string Message;
    public float Duration = 1f;
    private TextMeshProUGUI _text;
    
    void OnEnable()
    {
        _text = GetComponent<TextMeshProUGUI>();
        if (_text == null)
        {
            Debug.LogError("COULD NOT FIND TMP_UGUI");
        }
    }

    void Update()
    {
        if (Input.GetKeyUp(KeyCode.T))
        {
            ShowText(Message, null);
        }
    }

    public void ShowText(string message, UnityAction done )
    {
        Debug.Log("Showing " + message);
        float delay = Duration / message.Length;
        StartCoroutine(Type(message, delay, () =>
        {
            done.Invoke();
        }));
    }

    private IEnumerator Type(string message, float delay, UnityAction done)
    {
        string typing;
        int characters = message.Length;
        for (int i = 1; i <= characters; i++)
        {
            typing = message.Substring(0,i);
            _text.text = typing;
            yield return new WaitForSeconds(delay);
        }
        done.Invoke();
    }
}
