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

namespace SimplifyXR
{
    public class NavMenuItems : MonoBehaviour
    {

        public GameObject MenuItemButton;

        public float GetMenuItemsHeight()
        {
            var verticalLayout = this.GetComponent<VerticalLayoutGroup>();
            var buttons = this.GetComponentsInChildren<Button>();

            var spacing = verticalLayout.spacing * (buttons.Length + 1);
            var buttonHeight = buttons.Length > 0 ?
                buttons[0].GetComponent<RectTransform>().rect.height : 0;
            var buttonTotalHeight = buttons.Length * buttonHeight;

            return buttonTotalHeight + spacing;

        }

        public void RemoveMenuItemButton(PanelReference reference)
        {
            var root = this.GetComponentInParent<ElementRoot>();
            root.elements.RemoveAll(e => e.element == reference.panelButton);
            DestroyImmediate(reference.panelButton.gameObject);
        }

        public void UpdateOrCreateMenuItemButton(PanelReference reference)
        {
            if (reference.panelButton)
            {
                var navButton = reference.panelButton.GetComponent<NavButton>();
                navButton.UpdateButtonInfo(reference);
            }
            else
            {
                var button = Instantiate(MenuItemButton, this.transform);
                var navButton = button.GetComponent<NavButton>();
                reference.panelButton = navButton.GetComponent<Button>();

                navButton.UpdateButtonInfo(reference);

                var root = this.GetComponentInParent<ElementRoot>();
                var element = new Element();
                element.element = button.GetComponent<Button>();
                element.displayOptional = true;
                element.id = reference.buttonLabel + " Button";
                element.themeClass = ThemeClass.Primary;
                root.elements.Add(element);
            }

#if UNITY_EDITOR
            UnityEditor.EditorUtility.SetDirty(
                reference.panelButton.gameObject);
            UnityEditor.EditorUtility.SetDirty(
             this.GetComponentInParent<ElementRoot>());
#endif
        }
    }

}

