using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Toggle))]
public class DeformationToggle : MonoBehaviour {

    [SerializeField]
    private Image _icon;

    [SerializeField]
    private Text _nameField;


    public void Setup(DeformationManager deformationManager, BaseDeformation deformation, ToggleGroup toggleGroup)
    {
        Toggle toggle = GetComponent<Toggle>();
        _nameField.text = deformation.DeformationName;
        _icon.sprite = deformation.DeformationIcon;
        toggle.group = toggleGroup;
  
        
        toggle.onValueChanged.AddListener(toggleState =>
        {
            if (toggleState)
            {
                deformationManager.SetDeformationByName(deformation.GetType());
            }
        });

        deformationManager.OnDeformationChange += (newDeformation =>
        {
            

            if (newDeformation == deformation)
            {
                //avoid to call these events if value changed on different place
                int onValueChangedCount = toggle.onValueChanged.GetPersistentEventCount();
                for (int i = 0; i < onValueChangedCount; i++)
                {
                    toggle.onValueChanged.SetPersistentListenerState(0, UnityEngine.Events.UnityEventCallState.Off);
                }

                toggle.isOn = true;

                for (int i = 0; i < onValueChangedCount; i++)
                {
                    toggle.onValueChanged.SetPersistentListenerState(0, UnityEngine.Events.UnityEventCallState.RuntimeOnly);
                }
            }
        });

    }



}
