using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Utilities.Extensions;

namespace Canvases.Components
{
    public abstract class UISelectableComponentBase : UIComponentBase
    {
        public event Action OnSelected;

        protected Selectable Selectable = null;
        
        private EventTrigger.Entry selectEventTriggerEntry;
        private CanvasGroup parentCanvasGroup;
        
        private void Awake()
        {
            SetSelectableGameObject();
            AddSelectEventTrigger();
            parentCanvasGroup = gameObject.GetComponentInParents<CanvasGroup>();
        }

        protected abstract void SetSelectableGameObject();
        
        private void AddSelectEventTrigger()
        {
            EventTrigger eventTrigger = Selectable.gameObject.GetOrAddComponent<EventTrigger>();
            selectEventTriggerEntry = new EventTrigger.Entry
            {
                eventID = EventTriggerType.Select
            };
            selectEventTriggerEntry.callback.AddListener(OnSelectableSelected);
            eventTrigger.triggers.Add(selectEventTriggerEntry);
        }
        
        private void OnSelectableSelected(BaseEventData data)
        {
            if (!Selectable.interactable || parentCanvasGroup != null && !parentCanvasGroup.interactable)
                return;

            // Play select sound
            OnSelected?.Invoke();
        }

        protected virtual void OnDestroy()
        {
            selectEventTriggerEntry?.callback.RemoveListener(OnSelectableSelected);
        }
    }
}