using System; using System.Collections.Generic; using InABox.Core; namespace InABox.Configuration { public enum ConfigurationCacheType { Local, Global, User } public static class ConfigurationCache { private static readonly Dictionary> _localcache = new Dictionary>(); private static readonly Dictionary> _globalcache = new Dictionary>(); private static readonly Dictionary> _usercache = new Dictionary>(); private static readonly bool _shouldLog = false; private static Dictionary> GetCache(ConfigurationCacheType type) { return type == ConfigurationCacheType.Local ? _localcache : type == ConfigurationCacheType.Global ? _globalcache : _usercache; } private static void Log(LogType type, string message) { if (_shouldLog) { Logger.Send(type, "", message); } } public static T Check(ConfigurationCacheType type, string section) { Log(LogType.Information, $"- Checking {typeof(T)}({type},{section})"); var _cache = GetCache(type); if (_cache.ContainsKey(typeof(T))) { var subcache = _cache[typeof(T)]; if (subcache.ContainsKey(section)) { var data = subcache[section]; if (!string.IsNullOrWhiteSpace(data)) { Log(LogType.Information, $"- Checking: Found {typeof(T)}({type},{section}) -> {subcache[section]}"); var result = Serialization.Deserialize(subcache[section]); return result; } } } return default; } public static void Add(ConfigurationCacheType type, string section, T config) { Log(LogType.Information, $"- Adding {typeof(T)}({type},{section})"); var _cache = GetCache(type); if (!_cache.ContainsKey(typeof(T))) _cache[typeof(T)] = new Dictionary(); var subcache = _cache[typeof(T)]; subcache[section] = Serialization.Serialize(config); } public static void Clear(ConfigurationCacheType type, string section) { Log(LogType.Information, $"- Clearing {typeof(T)}({type},{section})"); var _cache = GetCache(type); if (_cache.ContainsKey(typeof(T))) { var subcache = _cache[typeof(T)]; if (subcache.ContainsKey(section)) { Log(LogType.Information, $"- Clearing: Removing {typeof(T)}({type},{section})"); subcache[section] = ""; } } } /// /// Clear the entire cache for a given cache type . Intended for use when the /// database server has changed and therefore the entire cache needs to be reset. /// /// The type of cache to clear. public static void ClearAll(ConfigurationCacheType type) { var _cache = GetCache(type); _cache.Clear(); } } }