initial chat options implementation

This commit is contained in:
Andriy
2023-07-20 20:24:16 +03:00
parent 46774bfd93
commit 8de8eac959
17 changed files with 420 additions and 5 deletions
+59
View File
@@ -0,0 +1,59 @@
using System;
using System.Reflection;
using System.Threading.Tasks;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
namespace Kruzya.TelegramBot.Core.Options;
public class DbOptionProvider : IOptionProvider
{
private readonly CoreContext _db;
public DbOptionProvider(CoreContext db)
{
_db = db;
}
public async Task<TValue> GetValueAsync<TOption, TValue>(long chatId)
{
return await GetValueAsync(
chatId,
GetOptionId<TOption>(),
GetDefaultValue<TOption, TValue>()
);
}
public async Task<TValue> GetValueAsync<TValue>(long chatId, string optionId, TValue defVal)
{
return (await _db.ChatOptionValues.FindOrCreateOption(chatId, optionId)).GetValue(defVal);
}
public async Task SetValueAsync<TOption, TValue>(long chatId, TValue value)
{
var chatOption = await _db.ChatOptionValues.FindOrCreateOption(chatId, GetOptionId<TOption>());
chatOption.SetValue(value);
_db.AddOrUpdate(chatOption);
}
protected OptionAttribute GetOptionAttribute<TOption>()
{
return typeof(TOption).GetCustomAttribute<OptionAttribute>();
}
protected string GetOptionId<TOption>()
{
var optionId = GetOptionAttribute<TOption>()?.OptionId;
if (optionId == null)
{
throw new ArgumentException("Option must implement OptionAttribute");
}
return optionId;
}
protected TValue GetDefaultValue<TOption, TValue>()
{
return (TValue) GetOptionAttribute<TOption>().DefaultValue;
}
}