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

public class DialogueScreen : MonoBehaviour
{
    [SerializeField]private Sprite[] _screenSprites;

	private Image _screenImage;

    private bool _stoped;

    private int _indexScreenSprites;
    // Start is called before the first frame update
    void Start()
    {
        _screenImage = GetComponent<Image>();
        _indexScreenSprites = 0;
        _stoped = false;
    }

    public void startAnimation()
    {
        _stoped = false;
        IEnumerator coroutine = animate();
        StartCoroutine(coroutine);
    }

    private IEnumerator animate()
    {
        yield return new WaitForSeconds(0.05f);
        while (true)
        {
            if(Input.GetKeyDown(KeyCode.Space) || _stoped)
            {
                restartSprite();
                yield break;
            }
            updateSprite();
            yield return new WaitForSeconds(0.1f);
        }
    }

    public void updateSprite()
    {
        if(_indexScreenSprites < _screenSprites.Length - 1)
        {
            _indexScreenSprites++;
        }

        else
        {
            _indexScreenSprites = 0;
        }

        _screenImage.sprite = _screenSprites[_indexScreenSprites];
        
    }

    public void restartSprite()
    {
        _stoped = true;
        _indexScreenSprites = 0;
        _screenImage.sprite = _screenSprites[_indexScreenSprites];
    }
}
