using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace eagle {
    public class GeneratedTextUpdater : MonoBehaviour, IClientTextListener {
        private string _textId;
        public string TextId {
            get => _textId;
            set {
                if (_textId != value) {
                    _textId = value;
                    _currentText = "";
                    _currentCompleted = false;

                    var scrollRect = GetComponentInParent<ScrollRect>(includeInactive: true);
                    if (scrollRect) { scrollRect.normalizedPosition = new Vector2(0, 1); }
                }

                if (!String.IsNullOrEmpty(_textId)) {
                    // If the text ID is set, we want to update the view immediately
                    // to reflect any existing text.
                    OnTextUpdate(ClientTextProvider.Provider.GetTextEntry(TextId));
                }
            }
        }

        private string _prefixedText = "";
        public string PrefixedText {
            get => _prefixedText;
            set {
                _prefixedText = value;
                OnTextUpdate(ClientTextProvider.Provider.GetTextEntry(TextId));
            }
        }

        private string _currentText = "";
        private bool _currentCompleted = false;

        public void Update() {
            if (!_currentCompleted) { UpdateView(); }
        }

        private void UpdateView() {
            if (String.IsNullOrEmpty(TextId)) {
                if (TextId == "") { GetComponent<TMP_Text>().text = PrefixedText; }

                return;
            }
            var text = _currentText;
            if (!_currentCompleted) {
                var millis = Time.time * 1000;
                var dots = (int)(millis / 100) % 4;
                for (var i = 0; i < dots; i++) { text += "."; }
            }

            GetComponent<TMP_Text>().text = PrefixedText + text;
        }

        private void OnTextUpdate(TextEntry entry) {
            if (entry != null) OnTextUpdate(entry.Text, entry.Completed);
        }

        public void OnTextUpdate(string text, bool completed) {
            _currentText = text;
            _currentCompleted = completed;
            UpdateView();
        }

        string IClientTextListener.TextId() { return _textId; }

        private void OnEnable() {
            ClientTextProvider.Provider.AddListener(this);

            if (!String.IsNullOrEmpty(TextId)) {
                OnTextUpdate(ClientTextProvider.Provider.GetTextEntry(TextId));
            }
        }

        private void OnDisable() { ClientTextProvider.Provider.RemoveListener(this); }
    }
}