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

[RequireComponent(typeof(CanvasGroup))]
public class GenericDialog : MonoBehaviour {
    public Text title;
    public Text message;
    public Text accept, decline;
    public Button acceptButton, declineButton;

    private CanvasGroup cg;

    void Awake() {
        cg = GetComponent<CanvasGroup>();
    }

    public GenericDialog SetOnAccept(string text, UnityAction action) {
        accept.text = text;
        acceptButton.onClick.RemoveAllListeners();
        acceptButton.onClick.AddListener(action);
        return this;
    }

    public GenericDialog SetOnDecline(string text, UnityAction action) {
        if (text.Equals("")) {
            declineButton.gameObject.SetActive(false);
        } else {
            declineButton.gameObject.SetActive(true);
            decline.text = text;
            declineButton.onClick.RemoveAllListeners();
            declineButton.onClick.AddListener(action);
        }
        return this;
    }

    public GenericDialog SetTitle(string title) {
        this.title.text = title;
        return this;
    }

    public GenericDialog SetMessage(string message) {
        this.message.text = message;
        return this;
    }

    public void Show() {
        this.transform.SetAsLastSibling();

        Transform iconPanel = GameObject.Find("IconPanel").GetComponent<Transform>();
        if (iconPanel.childCount == 0) {
            RectTransform rt = iconPanel.GetComponent<RectTransform>();
            rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 0);
            RectTransform rtd = GameObject.Find("DialogTitle").GetComponent<RectTransform>();
            rtd.offsetMin = new Vector2(0, rtd.offsetMin.y);
        }
        cg.blocksRaycasts = false;
        cg.alpha = 1f;
        cg.interactable = true;

        this.GetComponentInChildren<GenericDialog>().GetComponent<CanvasGroup>().blocksRaycasts = true;
    }

    public void Hide() {
        cg.interactable = false;
        cg.alpha = 0f;
        cg.blocksRaycasts = false;
    }

    private static GenericDialog instance;
    public static GenericDialog Instance() {
        if (!instance) {
            instance = FindObjectOfType(typeof(GenericDialog)) as GenericDialog;
            if (!instance) {
                Debug.Log("There need to be at least one active GenericDialog on the screen");
            }
        }
        return instance;
    }
}
