using System;
using JetBrains.Annotations;
using JohnsonUtils.Utilities;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace JohnsonUtils.Canvases
{
    public abstract class UISelectableComponentBase : UIComponentBase
    {
        [UsedImplicitly] 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;
            
            OnSelected?.Invoke();
        }

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