using System.Linq; using System.Threading.Tasks; using ChaosBot.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using JsonSerializer = System.Text.Json.JsonSerializer; 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 DatabaseContext dbContext = new DatabaseContext(); 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 SetValue(string key, T value, ulong guildId) { using DatabaseContext dbContext = new DatabaseContext(); Models.Configuration cnfSet = new Models.Configuration(); cnfSet.Key = key; cnfSet.DiscordGuildId = guildId; cnfSet.SerializedValue = JsonConvert.SerializeObject(value); dbContext.Configuration.Upsert(cnfSet) .On(x => new {x.Key, x.DiscordGuildId}) .Run(); } public static void DeleteValue(string key, ulong guildId) { using DatabaseContext dbContext = new DatabaseContext(); 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)); } } }