using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Variables;

public class SneakyTextController : MonoBehaviour
{
    [SerializeField]
    private Reference<float> m_lightLevel;

    [SerializeField]
    private Reference<bool> m_freezePlayer;

    [SerializeField]
    private Reference<bool> m_manuelDarknesscontrol;

    [SerializeField]
    private float m_time = 10;

    [SerializeField]
    private GameObject m_timerObject;


    [SerializeField]
    private TMPro.TextMeshProUGUI m_text;

    private bool m_hasTriggered = false;

    private void OnEnable()
    {
        m_lightLevel.OnValueChanged += OnLightChange;
    }

    private void OnDisable()
    {
        m_lightLevel.OnValueChanged -= OnLightChange;
    }


    private void Start()
    {
        m_text.gameObject.SetActive(false);
    }


    private void OnLightChange(float value)
    {

        Debug.Log("Here");

        if (!m_hasTriggered && !m_freezePlayer)
        {
            m_hasTriggered = true;
            StartCoroutine(Timer( m_time));
        }

    }

    private IEnumerator Timer(float time)
    {
        Debug.Log("Showing sneaky text");

        m_manuelDarknesscontrol.Value = true;

        float elapsedTime = 0;
        float fadeTime = 0.33f;

        m_text.gameObject.SetActive(true);

        Color color = m_text.color;

        while (elapsedTime< fadeTime)
        {

            m_lightLevel.Value = 1 - (elapsedTime / fadeTime);

            
            color.a = 1 - m_lightLevel;
            m_text.color = color;

            yield return new WaitForEndOfFrame();
            elapsedTime += Time.deltaTime;
        }

        m_lightLevel.Value = 0;
        color.a = 1 - m_lightLevel;
        m_text.color = color;

        m_timerObject.SetActive(false);

        Time.timeScale = 0.1f;



        elapsedTime = 0;
        fadeTime = 1.0f;

        while (elapsedTime < fadeTime)
        {

            Time.timeScale = 1 - (elapsedTime / fadeTime);

            yield return new WaitForEndOfFrame();
            elapsedTime += Time.unscaledDeltaTime;
        }




        yield return new WaitForSecondsRealtime(time);

        Time.timeScale = 1;

        m_timerObject.SetActive(true);


        


        elapsedTime = 0;
        fadeTime = 0.25f;

        while (elapsedTime < fadeTime)
        {

            m_lightLevel.Value = (elapsedTime / fadeTime);

            color.a = 1 - (elapsedTime / fadeTime);
            m_text.color = color;

            yield return new WaitForEndOfFrame();
            elapsedTime += Time.deltaTime;
        }

        m_text.gameObject.SetActive(false);
        m_manuelDarknesscontrol.Value = false;



    }

}
