using System.Globalization;
using System.Text.Json.Nodes;
using Microsoft.CommandPalette.Extensions.Toolkit;

namespace Olive.Helpers;

internal sealed class IntegerSetting : Setting<int>
{
  public IntegerSetting(string key, string label, string description, int defaultValue, int minimum, int maximum)
    : base(key, label, description, defaultValue)
  {
    Minimum = minimum;
    Maximum = maximum;
  }

  public int Minimum { get; }

  public int Maximum { get; }

  public string Placeholder { get; set; } = string.Empty;

  public override Dictionary<string, object> ToDictionary()
  {
    return new Dictionary<string, object>
    {
      { "type", "Input.Number" },
      { "title", Label },
      { "id", Key },
      { "label", Description },
      { "value", Value },
      { "placeholder", Placeholder },
      { "min", Minimum },
      { "max", Maximum },
      { "isRequired", IsRequired },
      { "errorMessage", ErrorMessage }
    };
  }

  public override void Update(JsonObject payload)
  {
    if (payload[Key] is null) return;

    int value;
    try
    {
      value = payload[Key]!.GetValue<int>();
    }
    catch (InvalidOperationException)
    {
      var text = payload[Key]?.GetValue<string>() ?? string.Empty;
      if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
      {
        ErrorMessage =
          $"Enter a number between {Minimum.ToString(CultureInfo.InvariantCulture)} and {Maximum.ToString(CultureInfo.InvariantCulture)}.";
        return;
      }
    }

    Value = Math.Clamp(value, Minimum, Maximum);
    ErrorMessage = string.Empty;
  }

  public override string ToState()
  {
    return $"\"{Key}\": {Value}";
  }
}
