2023-07-18 15:25:02 +03:00
|
|
|
using System.Text.Json.Nodes;
|
|
|
|
using Remora.Discord.Extensions.Formatting;
|
|
|
|
using Remora.Results;
|
|
|
|
|
|
|
|
namespace Boyfriend.Data.Options;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Represents an per-guild option.
|
|
|
|
/// </summary>
|
|
|
|
/// <typeparam name="T">The type of the option.</typeparam>
|
|
|
|
public class Option<T> : IOption
|
2023-08-02 23:51:16 +03:00
|
|
|
where T : notnull
|
|
|
|
{
|
|
|
|
protected readonly T DefaultValue;
|
2023-07-18 15:25:02 +03:00
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public Option(string name, T defaultValue)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
Name = name;
|
|
|
|
DefaultValue = defaultValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
public string Name { get; }
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public virtual string Display(JsonNode settings)
|
|
|
|
{
|
|
|
|
return Markdown.InlineCode(Get(settings).ToString() ?? throw new InvalidOperationException());
|
2023-07-18 15:25:02 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Sets the value of the option from a <see cref="string" /> to the provided JsonNode.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="settings">The <see cref="JsonNode" /> to set the value to.</param>
|
|
|
|
/// <param name="from">The string from which the new value of the option will be parsed.</param>
|
|
|
|
/// <returns>A value setting result which may or may not have succeeded.</returns>
|
2023-08-02 23:51:16 +03:00
|
|
|
public virtual Result Set(JsonNode settings, string from)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
settings[Name] = from;
|
|
|
|
return Result.FromSuccess();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the value of the option from the provided <paramref name="settings" />.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="settings">The <see cref="JsonNode" /> to get the value from.</param>
|
|
|
|
/// <returns>The value of the option.</returns>
|
2023-08-02 23:51:16 +03:00
|
|
|
public virtual T Get(JsonNode settings)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
var property = settings[Name];
|
|
|
|
return property != null ? property.GetValue<T>() : DefaultValue;
|
|
|
|
}
|
2023-09-22 20:23:08 +03:00
|
|
|
|
|
|
|
public Result Reset(JsonNode settings)
|
|
|
|
{
|
|
|
|
settings[Name] = null;
|
|
|
|
return Result.FromSuccess();
|
|
|
|
}
|
2023-07-18 15:25:02 +03:00
|
|
|
}
|