2023-07-18 15:25:02 +03:00
|
|
|
using System.Text.Json.Nodes;
|
|
|
|
using Remora.Commands.Parsers;
|
|
|
|
using Remora.Results;
|
|
|
|
|
2023-09-30 16:58:32 +03:00
|
|
|
namespace Octobot.Data.Options;
|
2023-07-18 15:25:02 +03:00
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public sealed class TimeSpanOption : Option<TimeSpan>
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
private static readonly TimeSpanParser Parser = new();
|
|
|
|
|
|
|
|
public TimeSpanOption(string name, TimeSpan defaultValue) : base(name, defaultValue) { }
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public override TimeSpan Get(JsonNode settings)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
var property = settings[Name];
|
|
|
|
return property != null ? ParseTimeSpan(property.GetValue<string>()).Entity : DefaultValue;
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public override Result Set(JsonNode settings, string from)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
if (!ParseTimeSpan(from).IsDefined(out var span))
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-07-28 19:58:55 +03:00
|
|
|
return new ArgumentInvalidError(nameof(from), Messages.InvalidSettingValue);
|
2023-08-02 23:51:16 +03:00
|
|
|
}
|
2023-07-18 15:25:02 +03:00
|
|
|
|
|
|
|
settings[Name] = span.ToString();
|
|
|
|
return Result.FromSuccess();
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
private static Result<TimeSpan> ParseTimeSpan(string from)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
return Parser.TryParseAsync(from).AsTask().GetAwaiter().GetResult();
|
|
|
|
}
|
|
|
|
}
|