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

[RequireComponent(typeof(TextMeshProUGUI))]
public class DialogueSystem : MonoBehaviour
{
    [SerializeField]private GameObject _nextEvent;
    private TextMeshProUGUI _textField;
    private string[] _texts;
    private bool _isDisplayed;
    private int _textsIndex;    
    private DialogueScreen _dialogueScreen;

    // Start is called before the first frame update
    void Awake()
    {
        _isDisplayed = false;
        _textsIndex = 0;        
    }

    public void InitDialogue()
    {
        _textField = GetComponent<TextMeshProUGUI>();               
        _texts = _textField.text.Split('|');
        _textField.text = "";
        _dialogueScreen = GameObject.FindGameObjectWithTag("DialogueScreen").GetComponent<DialogueScreen>();
        _dialogueScreen.startAnimation();
        IEnumerator coroutine = displayText();
        StartCoroutine(coroutine);
    }

    private IEnumerator displayText()
    {
        string text = _texts[_textsIndex];
        _textField.text = "";
        yield return new WaitForSeconds(0.05f);
        for (int i = 0; i < text.Length; i++) 
        {
            _textField.text += text[i];            
            if(Input.GetKeyDown(KeyCode.Space))
            {
                _textField.text = text;
                _textsIndex++;
                _isDisplayed = true;
                yield break;
            }

            yield return new WaitForSeconds(0.025f);
        }

        _textsIndex++;
        _isDisplayed = true;
        _dialogueScreen.restartSprite();
    }

    // Update is called once per frame
    void Update()
    {
        if(_isDisplayed && Input.GetKeyDown(KeyCode.Space) && _textsIndex < _texts.Length)
        {
            _isDisplayed = false;
            _dialogueScreen.startAnimation();
            IEnumerator coroutine = displayText();
            StartCoroutine(coroutine);
        }

        if(_isDisplayed && Input.GetKeyDown(KeyCode.Space) && _textsIndex == _texts.Length)
        {
            if(_nextEvent.GetComponent<DialogueSystem>() != null)
            {
                _nextEvent.SetActive(true);
                _isDisplayed = false;
                _textsIndex = 0;
                _textField.text = "";
                Destroy(this.gameObject);
            }

            else
            {
                Instantiate(_nextEvent, this.transform.position, Quaternion.identity);
                Destroy(this.gameObject);
            }
        }
    }
}
