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 GetValueAsync(long chatId) { return await GetValueAsync( chatId, GetOptionId(), GetDefaultValue() ); } public async Task GetValueAsync(long chatId, string optionId, TValue defVal) { return (await _db.ChatOptionValues.FindOrCreateOption(chatId, optionId)).GetValue(defVal); } public async Task SetValueAsync(long chatId, TValue value) { var chatOption = await _db.ChatOptionValues.FindOrCreateOption(chatId, GetOptionId()); chatOption.SetValue(value); _db.AddOrUpdate(chatOption); } protected OptionAttribute GetOptionAttribute() { return typeof(TOption).GetCustomAttribute(); } protected string GetOptionId() { var optionId = GetOptionAttribute()?.OptionId; if (optionId == null) { throw new ArgumentException("Option must implement OptionAttribute"); } return optionId; } protected TValue GetDefaultValue() { return (TValue) GetOptionAttribute().DefaultValue; } }