using System;
using Artemis.Storage.Entities.Plugins;
using Artemis.Storage.Repositories.Interfaces;
using Newtonsoft.Json;
using Stylet;
namespace Artemis.Core
{
///
/// Represents a setting tied to a plugin of type
///
/// The value type of the setting
public class PluginSetting : PropertyChangedBase
{
// ReSharper disable once NotAccessedField.Local
private readonly PluginInfo _pluginInfo;
private readonly IPluginRepository _pluginRepository;
private readonly PluginSettingEntity _pluginSettingEntity;
private T _value;
internal PluginSetting(PluginInfo pluginInfo, IPluginRepository pluginRepository, PluginSettingEntity pluginSettingEntity)
{
_pluginInfo = pluginInfo;
_pluginRepository = pluginRepository;
_pluginSettingEntity = pluginSettingEntity;
Name = pluginSettingEntity.Name;
try
{
Value = JsonConvert.DeserializeObject(pluginSettingEntity.Value);
}
catch (JsonReaderException)
{
Value = default;
}
}
///
/// The name of the setting, unique to this plugin
///
public string Name { get; }
///
/// The value of the setting
///
public T Value
{
get => _value;
set
{
if (!Equals(_value, value))
{
_value = value;
OnSettingChanged();
NotifyOfPropertyChange(nameof(Value));
}
}
}
///
/// Determines whether the setting has been changed
///
public bool HasChanged => JsonConvert.SerializeObject(Value) != _pluginSettingEntity.Value;
///
/// Resets the setting to the last saved value
///
public void RejectChanges()
{
Value = JsonConvert.DeserializeObject(_pluginSettingEntity.Value);
}
///
/// Saves the setting
///
public void Save()
{
if (!HasChanged)
return;
_pluginSettingEntity.Value = JsonConvert.SerializeObject(Value);
_pluginRepository.SaveSetting(_pluginSettingEntity);
}
///
/// Occurs when the value of the setting has been changed
///
public event EventHandler SettingChanged;
///
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);
}
}
}