using System;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.UI;

namespace Canvases.Components
{
    // ReSharper disable once InconsistentNaming Reason: UI should be capitalized
    public class ToggleUIComponent : UISelectableComponentBase
    {
        public event Action<bool> OnValueChanged;

        [Header("Association"), Required, SerializeField]
        private Toggle toggle;
        
        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;

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

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