using System; using System.Globalization; using System.IO; using System.Text; namespace Conjure.Arcade.Overlay.Settings { public class SerializableSettings : IDisposable where T : new() { private T? _current; // Make nullable private bool _currentExists; private readonly string _settingsPath; public SerializableSettings(string settingsName) { _settingsPath = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "Settings", $"{settingsName}.json" ); } public T Current { get { if (!_currentExists) { _current = new T(); _currentExists = true; } return _current!; // We know it's not null here } private set { _current = value; _currentExists = true; } } public void Save() { var directory = Path.GetDirectoryName(_settingsPath); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory!); File.WriteAllText(_settingsPath, System.Text.Json.JsonSerializer.Serialize(Current, new System.Text.Json.JsonSerializerOptions { WriteIndented = true })); } public void Load() { if (!File.Exists(_settingsPath)) { Save(); return; } var json = File.ReadAllText(_settingsPath); Current = System.Text.Json.JsonSerializer.Deserialize(json) ?? new T(); } private bool _disposed; public event EventHandler? OnDispose; public void Dispose() { if (!_disposed) { OnDispose?.Invoke(this, EventArgs.Empty); _disposed = true; } } } }