using System.Text.Json;
using System.Text.Json.Serialization;
namespace RioJoy.Core.Profiles;
///
/// Loads and saves as JSON. Replaces the legacy
/// SimpleIni single-file config with a profile library (see docs/PLAN.md).
///
public static class ConfigStore
{
private static readonly JsonSerializerOptions Options = new()
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() },
};
public static string Serialize(AppConfig config)
{
ArgumentNullException.ThrowIfNull(config);
return JsonSerializer.Serialize(config, Options);
}
public static AppConfig Deserialize(string json)
{
ArgumentException.ThrowIfNullOrWhiteSpace(json);
return JsonSerializer.Deserialize(json, Options)
?? throw new JsonException("Config JSON deserialized to null.");
}
/// Save the config to (creating directories).
public static void Save(AppConfig config, string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
string? dir = Path.GetDirectoryName(Path.GetFullPath(path));
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(path, Serialize(config));
}
///
/// Load the config from , or return a fresh default
/// if the file does not exist.
///
public static AppConfig Load(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
return File.Exists(path) ? Deserialize(File.ReadAllText(path)) : new AppConfig();
}
}