refactor settings load/save

- load using LINUQ
- load on child settings on demond
- prevent error when plugin has been removed
- prevent settings loose when plugin has been removed
This commit is contained in:
Pilzinsel64
2024-11-28 07:23:29 +01:00
parent 3070fab91b
commit 44ab301c24
3 changed files with 77 additions and 13 deletions

View File

@@ -1,4 +1,5 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
@@ -6,21 +7,29 @@ namespace Pilz.Configuration;
public class Settings : ISettings
{
[JsonProperty(nameof(Settings))]
protected readonly Dictionary<string, IChildSettings> mySettings = [];
protected readonly Dictionary<string, JObject> settingsJson = [];
protected readonly Dictionary<string, IChildSettings> settings = [];
protected JsonSerializerSettings serializerSettings;
[JsonIgnore]
public IReadOnlyCollection<IChildSettings> Childs => mySettings.Values;
public IReadOnlyCollection<IChildSettings> Childs => settings.Values;
public T Get<T>() where T : IChildSettings, ISettingsIdentifier
{
if (mySettings.TryGetValue(T.Identifier, out IChildSettings valueExisting) && valueExisting is T settingsExisting)
if (settings.TryGetValue(T.Identifier, out var valueExisting) && valueExisting is T settingsExisting)
return settingsExisting;
if (settingsJson.TryGetValue(T.Identifier, out var valueRaw)
&& valueRaw.ToObject<T>(JsonSerializer.CreateDefault(serializerSettings)) is T settingsDeserialized)
{
if (!settings.TryAdd(T.Identifier, settingsDeserialized))
settings[T.Identifier] = settingsDeserialized;
return settingsDeserialized;
}
if (Activator.CreateInstance<T>() is T settingsNew)
{
settingsNew.Reset();
mySettings.Add(T.Identifier, settingsNew);
settings.Add(T.Identifier, settingsNew);
return settingsNew;
}
@@ -29,7 +38,53 @@ public class Settings : ISettings
public void Reset()
{
foreach (var s in mySettings.Values)
foreach (var s in settings.Values)
s.Reset();
}
public string Save(JsonSerializerSettings serializerSettings)
{
this.serializerSettings = serializerSettings;
var serializer = JsonSerializer.CreateDefault(serializerSettings);
foreach (var kvp in settings)
{
var raw = JObject.FromObject(kvp.Value, serializer);
if (!settingsJson.TryAdd(kvp.Key, raw))
settingsJson[kvp.Key] = raw;
}
var objList = new JObject();
foreach (var kvp in settingsJson)
objList.Add(kvp.Key, kvp.Value);
var objSettings = new JObject
{
{ "Settings", objList }
};
return objSettings.ToString(serializer.Formatting);
}
public bool Load(JsonSerializerSettings serializerSettings, string raw)
{
this.serializerSettings = serializerSettings;
var objSettings = JObject.Parse(raw);
if (!objSettings.TryGetValue("Settings", out var tokenList) || tokenList is not JObject objList)
return false;
settingsJson.Clear();
settings.Clear();
foreach (var child in objList)
{
if (child.Value is not JObject value)
continue;
settingsJson.Add(child.Key, value);
}
return true;
}
}