using System.Collections;
using System.Collections.Generic;
using System.Net.Mime;
using UnityEngine;
using UnityEngine.UI;

using Singleton;
public class Subtitles : Singleton<Subtitles> {
    private Text displayText;
    [SerializeField] private float fadeSpeed = 0.2f;

    [SerializeField] private Animator progressAnimator;

    void Start() {
        displayText = GetComponent<Text>();
    }

    public void ShowProgressButton() {
        progressAnimator.SetTrigger("Show");
    }

    public void HideProgressButton() {
        progressAnimator.SetTrigger("Hide");
    }

    public void DisplayTextFirst(string text) {
        StartCoroutine(DisplayTextEnumFirst(text));
    }

    public void DisplayText(string text) {
        StartCoroutine(DisplayTextEnum(text));
    }

    public void DisplayText(string text, float speed) {
        StartCoroutine(DisplayTextEnumSpeed(text, speed));
    }

    IEnumerator DisplayTextEnumSpeed(string text, float speed) {
        yield return FadeoutEnumSpeed(speed);
        displayText.text = text;
        yield return FadeinEnumSpeed(speed);
    }

    IEnumerator FadeoutEnumSpeed(float speed) {
        while (!(displayText.color.a <= 0)) {
            var color = displayText.color;
            displayText.color = new Color(color.r, color.g, color.b, color.a - speed);
            yield return new WaitForEndOfFrame();
        }
    }

    IEnumerator FadeinEnumSpeed(float speed) {
        while (!(displayText.color.a >= 1)) {
            var color = displayText.color;
            displayText.color = new Color(color.r, color.g, color.b, color.a + speed);
            yield return new WaitForEndOfFrame();
        }
    }

    public void EndText() {
        Fadeout();
    }

    IEnumerator DisplayTextEnum(string text) {
        yield return FadeoutEnum();
        displayText.text = text;
        yield return FadeinEnum();
    }

    IEnumerator DisplayTextEnumFirst(string text) {
        yield return FadeoutEnum();
        displayText.text = text;
        yield return FadeinEnum();
    }


    private void Fadein() {
        StartCoroutine(FadeinEnum());
    }

    IEnumerator FadeinEnum() {
        while (!(displayText.color.a >= 1)) {
            var color = displayText.color;
            displayText.color = new Color(color.r, color.g, color.b, color.a + fadeSpeed * Time.deltaTime);
            yield return new WaitForEndOfFrame();
        }
    }

    private void Fadeout() {
        StartCoroutine(FadeoutEnum());
    }

    IEnumerator FadeoutEnum() {
        while (!(displayText.color.a <= 0)) {
            var color = displayText.color;
            displayText.color = new Color(color.r, color.g, color.b, color.a - fadeSpeed *Time.deltaTime);
            yield return new WaitForEndOfFrame();
        }
    }
}
