2023-02-08 23:53:42 +00:00
|
|
|
|
using System;
|
|
|
|
|
|
|
|
|
|
namespace SharpChat.Config {
|
|
|
|
|
public class CachedValue<T> {
|
|
|
|
|
private IConfig Config { get; }
|
|
|
|
|
private string Name { get; }
|
|
|
|
|
private TimeSpan Lifetime { get; }
|
2024-05-10 19:18:55 +00:00
|
|
|
|
private T? Fallback { get; }
|
2023-02-10 06:07:59 +00:00
|
|
|
|
private object ConfigAccess { get; } = new();
|
2023-02-08 23:53:42 +00:00
|
|
|
|
|
2024-05-10 19:18:55 +00:00
|
|
|
|
private object? CurrentValue { get; set; }
|
2023-02-08 23:53:42 +00:00
|
|
|
|
private DateTimeOffset LastRead { get; set; }
|
|
|
|
|
|
2024-05-10 19:18:55 +00:00
|
|
|
|
public T? Value {
|
2023-02-08 23:53:42 +00:00
|
|
|
|
get {
|
2023-02-10 06:07:59 +00:00
|
|
|
|
lock(ConfigAccess) { // this lock doesn't really make sense since it doesn't affect other config calls
|
2023-02-08 23:53:42 +00:00
|
|
|
|
DateTimeOffset now = DateTimeOffset.Now;
|
|
|
|
|
if((now - LastRead) >= Lifetime) {
|
|
|
|
|
LastRead = now;
|
|
|
|
|
CurrentValue = Config.ReadValue(Name, Fallback);
|
|
|
|
|
Logger.Debug($"Read {Name} ({CurrentValue})");
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-05-10 19:18:55 +00:00
|
|
|
|
return (T?)CurrentValue;
|
2023-02-08 23:53:42 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-10 19:18:55 +00:00
|
|
|
|
public static implicit operator T?(CachedValue<T> val) => val.Value;
|
2023-02-08 23:53:42 +00:00
|
|
|
|
|
2024-05-10 19:18:55 +00:00
|
|
|
|
public CachedValue(IConfig config, string name, TimeSpan lifetime, T? fallback) {
|
2023-02-08 23:53:42 +00:00
|
|
|
|
Config = config ?? throw new ArgumentNullException(nameof(config));
|
|
|
|
|
Name = name ?? throw new ArgumentNullException(nameof(name));
|
|
|
|
|
Lifetime = lifetime;
|
|
|
|
|
Fallback = fallback;
|
|
|
|
|
if(string.IsNullOrWhiteSpace(name))
|
|
|
|
|
throw new ArgumentException("Name cannot be empty.", nameof(name));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Refresh() {
|
2023-02-10 06:07:59 +00:00
|
|
|
|
LastRead = DateTimeOffset.MinValue;
|
2023-02-08 23:53:42 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override string ToString() {
|
2024-05-10 19:18:55 +00:00
|
|
|
|
return Value?.ToString() ?? string.Empty;
|
2023-02-08 23:53:42 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|