using System; using System.Diagnostics.CodeAnalysis; using Artemis.Core.Properties; using Artemis.Storage.Entities.Plugins; using Artemis.Storage.Repositories.Interfaces; using Newtonsoft.Json; namespace Artemis.Core { /// /// Represents a setting tied to a plugin of type /// /// The value type of the setting public class PluginSetting : CorePropertyChanged { // TODO: Why? Should have included that... // ReSharper disable once NotAccessedField.Local private readonly Plugin _plugin; private readonly IPluginRepository _pluginRepository; private readonly PluginSettingEntity _pluginSettingEntity; private T _value; internal PluginSetting(Plugin plugin, IPluginRepository pluginRepository, PluginSettingEntity pluginSettingEntity) { _plugin = plugin; _pluginRepository = pluginRepository; _pluginSettingEntity = pluginSettingEntity; Name = pluginSettingEntity.Name; try { _value = JsonConvert.DeserializeObject(pluginSettingEntity.Value, Constants.JsonConvertSettings); } catch (JsonReaderException) { _value = default!; } } /// /// The name of the setting, unique to this plugin /// public string Name { get; } /// /// The value of the setting /// [AllowNull] [CanBeNull] public T Value { get => _value; set { if (Equals(_value, value)) return; _value = value!; OnSettingChanged(); OnPropertyChanged(nameof(Value)); if (AutoSave) Save(); } } /// /// Determines whether the setting has been changed /// public bool HasChanged => JsonConvert.SerializeObject(Value, Constants.JsonConvertSettings) != _pluginSettingEntity.Value; /// /// Gets or sets whether changes must automatically be saved /// Note: When set to true is always false /// public bool AutoSave { get; set; } /// /// Resets the setting to the last saved value /// public void RejectChanges() { Value = JsonConvert.DeserializeObject(_pluginSettingEntity.Value, Constants.JsonConvertSettings); } /// /// Saves the setting /// public void Save() { if (!HasChanged) return; _pluginSettingEntity.Value = JsonConvert.SerializeObject(Value, Constants.JsonConvertSettings); _pluginRepository.SaveSetting(_pluginSettingEntity); OnSettingSaved(); } /// /// Occurs when the value of the setting has been changed /// public event EventHandler? SettingChanged; /// /// Occurs when the value of the setting has been saved /// public event EventHandler? SettingSaved; /// public override string ToString() { return $"{nameof(Name)}: {Name}, {nameof(Value)}: {Value}, {nameof(HasChanged)}: {HasChanged}"; } /// /// Invokes the event /// protected internal virtual void OnSettingChanged() { SettingChanged?.Invoke(this, EventArgs.Empty); } /// /// Invokes the event /// protected internal virtual void OnSettingSaved() { SettingSaved?.Invoke(this, EventArgs.Empty); } } }