76 lines
2.0 KiB
C#
76 lines
2.0 KiB
C#
using System;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace Conjure.Arcade.Overlay.Settings
|
|
{
|
|
public class SerializableSettings<T> : 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<T>(json) ?? new T();
|
|
}
|
|
|
|
private bool _disposed;
|
|
public event EventHandler? OnDispose;
|
|
|
|
public void Dispose()
|
|
{
|
|
if (!_disposed)
|
|
{
|
|
OnDispose?.Invoke(this, EventArgs.Empty);
|
|
_disposed = true;
|
|
}
|
|
}
|
|
}
|
|
} |