using System;
using UnityEngine;
using UnityEngine.UI;

public sealed class DialogUI : MonoBehaviour
{
    [SerializeField]
    private Text titleLabels = null;
    [SerializeField]
    private Text questionLabel = null;
    [SerializeField]
    private DialogUIItem[] answerItems = null;

    public Action<int> result = null;
    public const int DefaultActionId = -1;

    public void Show(string question, string[] answers = null, string title = null, Action<int> resultCallback = null)
    {
        gameObject.SetActive(true);
        result = resultCallback;
        questionLabel.text = question ?? string.Empty;
        titleLabels.text = title ?? string.Empty;
        if (string.IsNullOrEmpty(title))
            titleLabels.gameObject.SetActive(false);
        for (int i = 0; i < answerItems.Length; i++) {
            if (answers != null && i < answers.Length)
            {
                answerItems[i].Show(answers[i]);
            }
            else
            {
                answerItems[i].Hide();
            }
        }
    }

    public void Hide()
    {
        gameObject.SetActive(false);
    }

    // Call from editor
    public void OnSelectAnswer(int id)
    {
        Hide();
        InvokeSafe(id);
    }

    // Call from editor
    private void ExitDaialog()
    {
        Hide();
        InvokeSafe(DefaultActionId);
    }

    private void InvokeSafe(int action)
    {
        var cacheAction = result;
        result = null;
        cacheAction?.Invoke(action);
    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            ExitDaialog();
        }
    }
}
