using System.Linq; using System.Text.Json; using ChaosBot.Models; using Microsoft.Extensions.Configuration; namespace ChaosBot.ConfigHelpers { internal static class ConfigurationRepository { public static T GetValue(string key, ulong guildId) { return GetValue(key, guildId, default); } public static T GetValue(string key, ulong guildId, T defaultValue) { using (ChaosbotContext dbContext = new ChaosbotContext()) { Models.Configuration config = dbContext.Configuration .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); if (config == null || string.IsNullOrEmpty(config.SerializedValue)) return GetValueFromAppSettings(key, guildId, defaultValue); return JsonSerializer.Deserialize(config.SerializedValue); } } public static void DeleteValue(string key, ulong guildId) { using (ChaosbotContext dbContext = new ChaosbotContext()) { Models.Configuration config = dbContext.Configuration .SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key); if (config == null) return; dbContext.Remove(config); dbContext.SaveChanges(); } } private static T GetValueFromAppSettings(string key, ulong guildId, T defaultValue) { return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue)); } } }