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

public class DialogBoxes : MonoBehaviour
{

    [Header("Dialog Messages:")]
    [SerializeField] string[] dialogMessages;
    private TMP_Text textField;
    private int messageCount = 0;

    [Header("Images:")]
    [SerializeField] Image backgroundImageObject;
    [SerializeField] Sprite[] images;

    [Header("Buttons:")]
    [SerializeField] GameObject backToMenuButton;


    // Start is called before the first frame update
    void Start()
    {
        textField = this.gameObject.GetComponent<TMP_Text>();
        ReconfigureSpriteArray();
        textField.text = dialogMessages[0];
        backgroundImageObject.sprite = images[0];
    }

    void OnAdvanceDialog()
    {
        messageCount += 1;
        if (messageCount < dialogMessages.Length)
        {
            textField.text = dialogMessages[messageCount];
            backgroundImageObject.sprite = images[messageCount];
        }
        else
        { // no more dialog messages, advance the scene
            if (backToMenuButton != null) {
                backToMenuButton.SetActive(true);
            } else {
                SceneController.Instance.NextScene();
            }
        }
    }

    void ReconfigureSpriteArray()
    {
        // resize if need to
        if (images.Length != dialogMessages.Length)
        {
            Sprite[] newImagesArray = new Sprite[dialogMessages.Length];
            for (int i = 0; i < newImagesArray.Length; i++)
            {
                newImagesArray[i] = images[i];
            }
            images = newImagesArray;
        }

        // update empty slots
        for (int i = 1; i < images.Length; i++)
        {
            if (images[i] == null)
            {
                images[i] = images[i - 1];
            }
        }

    }
}
