using System; using global::System.IO; using global::Newtonsoft.Json.Linq; namespace Pilz.Configuration { public sealed class SettingsManager : ISettingsManager where T : SettingsBase { public event EventHandler AutoSavingSettings; public event EventHandler SavingSettings; public event EventHandler SavedSettings; private T defaultInstance = null; private bool enableAutoSave = false; private bool addedHandler = false; public string ConfigFilePath { get; set; } public bool AutoSaveOnExit { get { return enableAutoSave; } set { if (enableAutoSave != value) { enableAutoSave = value; switch (enableAutoSave) { case true: { if (!addedHandler) { AddAutoSaveHandler(); } break; } case false: { if (addedHandler) { RemoveAutoSaveHandler(); } break; } } } } } private void AddAutoSaveHandler() { System.Windows.Forms.Application.ApplicationExit += AutoSaveSettingsOnExit; addedHandler = true; } private void RemoveAutoSaveHandler() { System.Windows.Forms.Application.ApplicationExit -= AutoSaveSettingsOnExit; addedHandler = false; } public T Instance { get { if (defaultInstance is null) { Load(); } return defaultInstance; } } public SettingsManager() { ConfigFilePath = ""; AutoSaveOnExit = false; } public SettingsManager(string fileName, bool autoSaveOnExit) { ConfigFilePath = fileName; AutoSaveOnExit = autoSaveOnExit; } private void AutoSaveSettingsOnExit(object sender, EventArgs e) { AutoSavingSettings?.Invoke(this, new EventArgs()); Save(); } public void Save() { if (!string.IsNullOrEmpty(ConfigFilePath) && defaultInstance is object) { SavePrivate(); } } public void Load() { if (!string.IsNullOrEmpty(ConfigFilePath) && File.Exists(ConfigFilePath)) { LoadPrivate(); } else { CreateNewInstance(); } if (defaultInstance is object) { defaultInstance._settingsManager = this; } } public void Reset() { Instance.ResetValues(); } private void CreateNewInstance() { var ctor = typeof(T).GetConstructor(Array.Empty()); if (ctor is object) { defaultInstance = (T)ctor.Invoke(Array.Empty()); defaultInstance.ResetValues(); } else { throw new Exception("The base type has no constructor with no parameters."); } } private void LoadPrivate() { defaultInstance = JObject.Parse(File.ReadAllText(ConfigFilePath)).ToObject(); } private void SavePrivate() { SavingSettings?.Invoke(this, new EventArgs()); var obj = JObject.FromObject(defaultInstance); if (obj is object) { File.WriteAllText(ConfigFilePath, obj.ToString()); } SavedSettings?.Invoke(this, new EventArgs()); } } }