using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class MessageHandler : MonoBehaviour
{
    public float timeToHide = 3;

    public Button button1;
    public Button button2;
    
    private TextMeshProUGUI text;
    
    void Start()
    {
        text = GetComponent<TextMeshProUGUI>();
        EmptyText();
    }

    private bool canProcess = true;
    
    public void NewText(string newText, UnityAction action1 = null, string button1Text = "",
        UnityAction action2 = null, string button2Text = "")
    {
        if (!canProcess)
            return;
        
        CancelInvoke("EmptyText");
        text.SetText(newText);
        if (action1 == null && action2 == null)
        Invoke("EmptyText",timeToHide);

        if (action1 != null)
        {
            button1.gameObject.SetActive(true);
            button1.GetComponentInChildren<TextMeshProUGUI>().text = button1Text;
            canProcess = false;
            button1.onClick.AddListener(() =>
            {
                canProcess = true;
                button1.onClick.RemoveAllListeners();
                button1.gameObject.SetActive(false);
                action1.Invoke();
            });
        }
        
        if (action2 != null)
        {
            button2.gameObject.SetActive(true);
            button2.GetComponentInChildren<TextMeshProUGUI>().text = button2Text;
            canProcess = false;
            button2.onClick.AddListener(() =>
            {
                canProcess = true;
                button2.onClick.RemoveAllListeners();
                button2.gameObject.SetActive(false);
                action2.Invoke();
            });
        }
    }
    
    private void EmptyText()
    {
        text.text = "";
    }
}
