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

[RequireComponent(typeof(TextMeshProUGUI))]
public class RoundsLeft : MonoBehaviour
{

    [SerializeField]
    private GameModeReference reference;


    [SerializeField]
    private float DisplayTime;

    [SerializeField]
    private AnimationCurve AnimationCurve;


    private ColorGameMode gameMode;
    private TextMeshProUGUI Text;

    private void Awake()
    {
        Text = GetComponent<TextMeshProUGUI>();
        gameMode = reference.Value as ColorGameMode;

        Text.enabled = false;
    }


    [ContextMenu("Do Animation")]
    public void StartAnimation()
    {
        //UpdateText();


        Vector3 startPosition = new Vector3(Screen.width * 2, 0, 0);
        Vector3 endPosition = new Vector3(-Screen.width * 2, 0 , 0);
        StartCoroutine(AnimationRoutine(startPosition, endPosition));
    }

    private void UpdateText()
    {
        if (gameMode == null) {
            Text.text = "New Round";
            return;
        }

        int RoundsLeft = gameMode.MaxRound - gameMode.RoundCount;
        if (RoundsLeft == 1)
            Text.text = "Last Round";
        else
            Text.text = RoundsLeft + " Rounds Left";
    }

    public IEnumerator AnimationRoutine(Vector3 startPos, Vector3 endPos)
    {
        RectTransform rt = transform as RectTransform;
        Text.enabled = true;

        float ratio;
        float elapsedTime = 0;
        while (elapsedTime < DisplayTime)
        {
            ratio = AnimationCurve.Evaluate(elapsedTime/DisplayTime);
            rt.anchoredPosition = Vector3.Lerp(startPos, endPos, ratio);

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

        ratio = AnimationCurve.Evaluate(1);
        rt.anchoredPosition = Vector3.Lerp(startPos, endPos, ratio);

        Text.enabled = false;
    }


}
