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

namespace TyphoonUI
{
    [RequireComponent(typeof(TextMeshProUGUI))]
    [ExecuteInEditMode]
    public class LoopTextMeshPro : MonoBehaviour
    {
        public TextMeshProUGUI Target;

        public List<string> Texts = new List<string>();
        public bool IsPlaying = false;
        public float Delay = 0.5f;
        public float PlayingTime = 0;
        public int LastIndex = 0;

        private void Reset()
        {
            Target = transform.GetComponent<TextMeshProUGUI>();
        }

        public void Play()
        {
            PlayingTime = 0;
            IsPlaying = true;
            LastIndex = 0;
            if (Texts.Count > 0)
            {
                Target.text = Texts[LastIndex % Texts.Count];
            }
        }

        public void Play(string[] texts, float delay)
        {
            Texts = texts.ToList();
            Delay = delay;
            Play();
        }

        public void Stop()
        {
            IsPlaying = false;
        }


        private void Update()
        {
            if (!IsPlaying || Texts.Count <= 0)
            {
                return;
            }

            PlayingTime += Time.deltaTime;
            if (PlayingTime > Delay)
            {
                LastIndex += 1;
                PlayingTime %= Delay;
                Target.text = Texts[LastIndex % Texts.Count];
            }
        }
    }
}