using UnityEngine;
using UnityEngine.Events;

namespace Shared.ScriptableVariables {
  // Component to tie Unity's event system to variable values based on conditions
  public class Vector2VariableComparison : MonoBehaviour {
    [Tooltip("The variable we are watching value changes to compare against something else")]
    public Vector2Variable variable;

    [Tooltip("Scriptable Variable to compare, if null then comparison value will be used to compare")]
    public Vector2Variable comparisonVariable;

    [Tooltip("Hardcoded value to compare against variable if comparisonVariable isn't set")]
    public Vector2 comparisonValue;

    [Tooltip("Fires if variable changes and its value is equal to the comparison amount")]
    public UnityEvent onEqual;

    [Tooltip("Fires if variable changes and its value is not equal to the comparison amount")]
    public UnityEvent onNotEqual;

    [Tooltip("Fires true or false if the values are equal whenever variable's value changes")]
    public BooleanUnityEvent onValueChanged;

    // --------------------------------------------------------------------------
    void OnEnable() {
      variable.OnValueChanged += OnValueChanged;
      OnValueChanged();
    }

    // --------------------------------------------------------------------------
    void OnDisable() {
      variable.OnValueChanged -= OnValueChanged;
    }

    // --------------------------------------------------------------------------
    private void OnValueChanged() {
      var equal = variable.Value == (comparisonVariable != null ? comparisonVariable.Value : comparisonValue);
      if (equal) {
        onEqual?.Invoke();
      }
      else {
        onNotEqual?.Invoke();
      }
      onValueChanged?.Invoke(equal);
    }
  }
}