diff --git a/JackCraft.Config/Config.cs b/JackCraft.Config/Config.cs new file mode 100644 index 0000000..f633fbd --- /dev/null +++ b/JackCraft.Config/Config.cs @@ -0,0 +1,82 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace JackCraft.Config; + +public class Config +{ + private readonly FileInfo _configFile; + public readonly string ConfigFileName; + public readonly string ConfigFilePath; + private Dictionary _configData = null!; + + public Config(FileInfo configFile) + { + _configFile = configFile; + ConfigFilePath = configFile.DirectoryName ?? string.Empty; + ConfigFileName = configFile.Name; + if (!configFile.Exists) + { + configFile.Directory?.Create(); + using var stream = configFile.Create(); + File.WriteAllText(configFile.FullName, "{}"); + } + + LoadConfigData(); + } + + private void LoadConfigData() + { + if (File.Exists(_configFile.FullName)) + { + var existingJson = File.ReadAllText(_configFile.FullName); + _configData = JsonConvert.DeserializeObject>(existingJson) ?? + new Dictionary(); + } + else + { + _configData = new Dictionary(); + } + } + + public T? Get(string key, T? defaultValue) + { + var keys = key.Split('.'); + var currentData = _configData; + for (var i = 0; i < keys.Length - 1; i++) + { + if (!currentData.TryGetValue(keys[i], out var tValue)) return defaultValue; + if (tValue is JObject jObject) + currentData = jObject.ToObject>(); + else if (tValue is Dictionary nestedDict) + currentData = nestedDict; + else + return defaultValue; + } + + if (currentData.TryGetValue(keys[^1], out var result) && result is T typedResult) return typedResult; + + return defaultValue; + } + + public void Set(string key, T? value) + { + var keys = key.Split('.'); + var currentData = _configData; + for (var i = 0; i < keys.Length - 1; i++) + { + if (!currentData.TryGetValue(keys[i], out var tValue) || + tValue is not Dictionary nestedDict) + { + nestedDict = new Dictionary(); + currentData[keys[i]] = nestedDict; + } + + currentData = nestedDict; + } + + currentData[keys[^1]] = (object?)value ?? string.Empty; + var json = JsonConvert.SerializeObject(_configData, Formatting.Indented); + File.WriteAllText(_configFile.FullName, json); + } +} \ No newline at end of file