79 lines
2.1 KiB
C#
79 lines
2.1 KiB
C#
using System.Reflection;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
namespace BangumiRenamer.ConfigManager;
|
|
|
|
public class ConfigManager(string configPath)
|
|
{
|
|
private static readonly Dictionary<Type, string> Cache = new();
|
|
private readonly Dictionary<string, object> _configObjects = new();
|
|
private readonly Dictionary<string, JObject> _configs = new();
|
|
|
|
private static string GetConfigName(Type type)
|
|
{
|
|
if (Cache.TryGetValue(type, out var name)) return name;
|
|
name = type.Name;
|
|
if(type.GetCustomAttribute(typeof(ConfigItemAttribute)) is ConfigItemAttribute info)
|
|
{
|
|
name = string.IsNullOrEmpty(info.Name) ? type.Name : info.Name;
|
|
}
|
|
Cache[type] = name;
|
|
return name;
|
|
}
|
|
|
|
public T Get<T>() where T : class, new()
|
|
{
|
|
var name = GetConfigName(typeof(T));
|
|
if (_configObjects.TryGetValue(name, out var value))
|
|
{
|
|
return (T) value;
|
|
}
|
|
T result;
|
|
if (_configs.TryGetValue(name, out var jObject))
|
|
{
|
|
result = jObject.ToObject<T>();
|
|
}
|
|
else
|
|
{
|
|
result = new T();
|
|
}
|
|
_configObjects[name] = result;
|
|
return result;
|
|
}
|
|
|
|
public void Reset<T>()
|
|
{
|
|
var name = GetConfigName(typeof(T));
|
|
_configs.Remove(name);
|
|
_configObjects.Remove(name);
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
_configs.Clear();
|
|
_configObjects.Clear();
|
|
}
|
|
|
|
public void Load()
|
|
{
|
|
_configs.Clear();
|
|
_configObjects.Clear();
|
|
if (!File.Exists(configPath)) return;
|
|
var configJson = File.ReadAllText(configPath);
|
|
var config = JObject.Parse(configJson);
|
|
foreach (var kv in config)
|
|
{
|
|
_configs[kv.Key] = kv.Value.ToObject<JObject>();
|
|
}
|
|
}
|
|
|
|
public void Save()
|
|
{
|
|
foreach (var config in _configObjects)
|
|
{
|
|
_configs[config.Key] = JObject.FromObject(config.Value);
|
|
}
|
|
File.WriteAllText(configPath, JsonConvert.SerializeObject(_configs, Formatting.Indented));
|
|
}
|
|
} |