using System.Collections.Generic;
using Eagle0.Tutorial;
using UnityEngine;
using UnityEngine.UI;

namespace eagle {
    public class CommandButtonPanelController : MonoBehaviour {
        public GameObject buttonsContainer;
        public Button buttonPrefab;
        public EagleGameController gameController;

        private List<string> _registeredTargetIds = new List<string>();

        void Start() { ClearButtonContents(); }

        public void SetButtonContents(GUIContent[] contents) {
            ClearButtonContents();

            var registry = TutorialManager.Instance?.TargetRegistry;
            int contentsCount = contents.Length;
            for (int i = 0; i < contentsCount; i++) {
                int buttonIndex = i;
                var newButton = Instantiate(buttonPrefab, buttonsContainer.transform);
                newButton.GetComponentInChildren<RawImage>().texture = contents[buttonIndex].image;
                newButton.onClick.AddListener(() => gameController.SelectButtonIndex(buttonIndex));

                var tooltipTextProvider = newButton.GetComponent<HoveringTooltipTextProvider>();
                tooltipTextProvider.text = contents[buttonIndex].tooltip;

                if (registry != null && !string.IsNullOrEmpty(contents[buttonIndex].tooltip)) {
                    string targetId = contents[buttonIndex].tooltip.Replace(" ", "") + "Button";
                    var rt = newButton.GetComponent<RectTransform>();
                    if (rt != null) {
                        registry.RegisterTarget(targetId, rt);
                        _registeredTargetIds.Add(targetId);
                    }
                }
            }
        }

        public void ClearButtonContents() {
            var registry = TutorialManager.Instance?.TargetRegistry;
            if (registry != null) {
                foreach (var id in _registeredTargetIds) { registry.UnregisterTarget(id); }
            }
            _registeredTargetIds.Clear();

            int childCount = buttonsContainer.transform.childCount;
            for (int i = childCount - 1; i >= 0; i--) {
                Destroy(buttonsContainer.transform.GetChild(i).gameObject);
            }
        }
    }
}
