using System;
using JetBrains.Annotations;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.UI;
#if ODIN_INSPECTOR
#endif

namespace JohnsonUtils.Canvases
{
    public class ToggleUIComponent : UISelectableComponentBase
    {
        [UsedImplicitly] public event Action<bool> OnValueChanged;

#if ODIN_INSPECTOR
        [Required]
#endif
        [Header("Association"), SerializeField]
        private Toggle toggle;
        
        [PublicAPI]
        public bool IsOn => toggle.isOn;

        private void Start()
        {
            Debug.Assert(toggle, $"A {nameof(toggle)} must be assigned to a {nameof(Toggle)}");
            toggle.onValueChanged.AddListener(OnToggleChanged);
        }

        protected override void OnDestroy()
        {
            toggle.onValueChanged.RemoveListener(OnToggleChanged);
            base.OnDestroy();
        }

        protected override void SetSelectableGameObject() => Selectable = toggle;

        [PublicAPI]
        public void Invert() => toggle.isOn = !toggle.isOn;
        
        private void OnToggleChanged(bool value) => OnValueChanged?.Invoke(value);

        private void OnValidate()
        {
            if (!toggle)
                toggle = GetComponent<Toggle>();
        }
    }
}