using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class EndingStoryControl : MonoBehaviour
{
    public Text StoryText;
    public int CurrentTextLineIndex;
    public Image Sprite;
    public AudioClip TypeSoundEffect;
    public bool ShowingStory;

    public bool EndLineImmediate;

    public void StartEndingStory()
    {
        AudioManager.Instance.PlayBGM(GameplayManager.Instance.BGMs[Random.Range(0, GameplayManager.Instance.BGMs.Count)]);
        ShowNextText();
    }

    public void ShowNextText()
    {
        if (ShowingStory)
        {
            EndLineImmediate = true;
        }
        else
        {
            EndLineImmediate = false;
            if (CurrentTextLineIndex > GameplayManager.Instance.EndGameTextLines.Count)
            {
                int scene = SceneManager.GetActiveScene().buildIndex;
                SceneManager.LoadScene(scene, LoadSceneMode.Single);
            }
            else
            {
                AudioManager.Instance.PlaySoundEffect(AudioManager.Instance.GenericClick);
                ShowingStory = true;
                StoryText.text = "";
                StartCoroutine(ShowNextTextHelper());
            }
        }
    }

    IEnumerator ShowNextTextHelper()
    {
        Sprite.gameObject.SetActive(false);

        string nextline ="";
        if (CurrentTextLineIndex == GameplayManager.Instance.EndGameTextLines.Count)
        {
            nextline = "The end . . .";
        }
        else
        {
            nextline = GameplayManager.Instance.EndGameTextLines[CurrentTextLineIndex];
        }
        for (int i = 0; i < nextline.Length; i++)
        {
            AudioManager.Instance.PlaySoundEffect(TypeSoundEffect);
            StoryText.text += nextline[i];
            if (!EndLineImmediate)
            {
                yield return new WaitForSeconds(Time.deltaTime * 2);
            }
        }
        if (CurrentTextLineIndex < GameplayManager.Instance.EndGameTextLines.Count && 
            GameplayManager.Instance.EndGameImages[CurrentTextLineIndex] != null)
        {
            Sprite.sprite = GameplayManager.Instance.EndGameImages[CurrentTextLineIndex];
            Sprite.gameObject.SetActive(true);
        }
        else
        {
            Sprite.gameObject.SetActive(false);
        }
        CurrentTextLineIndex++;

        yield return new WaitForSeconds(0.5f);
        ShowingStory = false;
    }
}
