using System;
using UnityEngine;
using TMPro;

namespace Shared.SEUI {
  // Base class for read only UI for a ScriptableVariable
  public abstract class ScriptableVariableLabel<T> : MonoBehaviour {
    [Tooltip("The optional Text where we are putting the variable's name")]
    public TMP_Text nameLabel;

    [Tooltip("The optional Text where we are putting the variable's value")]
    public TMP_Text valueLabel;

    [Tooltip("The C# String.Format() string for displaying the value")]
    public string format;

    //---------------------------------------------------------------------------
    void Start() {
      if (nameLabel != null) {
        nameLabel.text = GetName();
      }
    }

    //---------------------------------------------------------------------------
    void Update() {
      if (valueLabel != null) {
        var valueString = GetValueString();
        if (valueLabel.text != valueString) {
          valueLabel.text = valueString;
        }
      }
      // The component doesn't need to update if it has no place to display the value
      else {
        enabled = false;
      }
    }

    //---------------------------------------------------------------------------
    // Implement with how to get the ScriptableVariable's name
    protected abstract string GetName();

    //---------------------------------------------------------------------------
    // Implement with how to get the ScriptableVariable's value
    protected abstract T GetValue();

    //---------------------------------------------------------------------------
    // Format the current value into a string
    private string GetValueString() {
      var value = GetValue();
      if (String.IsNullOrEmpty(format)) {
        return value.ToString();
      }
      return String.Format(format, value);
    }
  }
}