using System;
using UnityEngine;
using UnityEngine.Events;
using TMPro;
using Shared.ScriptableVariables;

namespace Shared.SEUI {
  // UI Editor for an IntVariable
  // Depends on ScriptableVariable package
  public class IntVariableInput : ScriptableVariableInput<int> {
    [Tooltip("The variable we are editing")]
    public IntVariable variable;

    [Tooltip("The input UI to edit the variable's value with")]
    public TMP_InputField input;

    // Temporary callback to bridge value changes in the UI and the variable
    private UnityAction<string> valueConverter;

    //---------------------------------------------------------------------------
    void Start() {
      // Make sure the input handles the right content type
      input.contentType = TMP_InputField.ContentType.IntegerNumber;
    }

    //---------------------------------------------------------------------------
    protected override void AddUIListener(UnityAction<int> callback) {
      // Define the value converting bridge callback to add to the UI listener
      valueConverter = delegate(string value) {
        if (!String.IsNullOrEmpty(input.text)) {
          callback(Convert.ToInt32(value));
        }
        else {
          callback(0);
        }
      };

      input.onValueChanged.AddListener(valueConverter);
    }

    //---------------------------------------------------------------------------
    protected override void RemoveUIListener(UnityAction<int> callback) {
      if (valueConverter != null) {
        input.onValueChanged.RemoveListener(valueConverter);
        valueConverter = null;
      }
    }

    //---------------------------------------------------------------------------
    protected override bool DoValuesMatch() {
      return !String.IsNullOrEmpty(input.text) && input.text == variable.Value.ToString();
    }

    //---------------------------------------------------------------------------
    protected override void UpdateUIValue() {
      input.SetTextWithoutNotify(variable.Value.ToString());
    }

    //---------------------------------------------------------------------------
    protected override void UpdateVariableValue(int value) {
      variable.Value = value;
    }
  }
}