using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class InputErrorMessage : MonoBehaviour
{
    [SerializeField] Image m_background;
    [SerializeField] TextMeshProUGUI m_text;

    [SerializeField] GameLauncher m_gameLauncher;
    IEnumerator co_flash;

    private void Awake()
    {
        m_gameLauncher = FindObjectOfType<GameLauncher>();
    }

    private void OnEnable()
    {
        if (!m_gameLauncher)
            return;

        m_gameLauncher.OnJoinFailed += FlashMessage;
    }

    private void OnDisable()
    {
        if (!m_gameLauncher)
            return;

        m_gameLauncher.OnJoinFailed -= FlashMessage;
    }

    // Start is called before the first frame update
    void Start()
    {
        SetImageTextOpacity(0);
    }

    void SetImageTextOpacity(float _perc)
    {
        if (m_background)
        {
            Color _bgCol = m_background.color;
            m_background.color = new Color(_bgCol.r, _bgCol.g, _bgCol.b, _perc);
        }

        if (m_text)
        {
            Color _tmpCol = m_text.color;
            m_text.color = new Color(_tmpCol.r, _tmpCol.g, _tmpCol.b, _perc);
        }
    }

    public void FlashMessage()
    {
        if (co_flash != null)
        {
            StopCoroutine(co_flash);
            co_flash = null;
        }
        
        co_flash = Flash();
        StartCoroutine(co_flash);
    }

    IEnumerator Flash()
    {
        SetImageTextOpacity(1);

        yield return new WaitForSecondsRealtime(1.5f);

        for (float t = 1.5f; t > 0; t -= Time.unscaledDeltaTime)
        {
            SetImageTextOpacity(t / 1.5f);

            yield return null;
        }

        SetImageTextOpacity(0);

        co_flash = null;

        yield break;
    }
}
