using System;
using System.Text.Json;
using Artemis.Storage.Entities.Plugins;
using Artemis.Storage.Repositories.Interfaces;
namespace Artemis.Core;
///
/// Represents a setting tied to a plugin of type
///
/// The value type of the setting
public class PluginSetting : CorePropertyChanged, IPluginSetting
{
private readonly IPluginRepository _pluginRepository;
private readonly PluginSettingEntity _pluginSettingEntity;
private T _value;
internal PluginSetting(IPluginRepository pluginRepository, PluginSettingEntity pluginSettingEntity)
{
_pluginRepository = pluginRepository;
_pluginSettingEntity = pluginSettingEntity;
Name = pluginSettingEntity.Name;
try
{
_value = CoreJson.Deserialize(pluginSettingEntity.Value)!;
}
catch (JsonException)
{
_value = default!;
}
}
///
/// The value of the setting
///
public T? Value
{
get => _value;
set
{
if (Equals(_value, value)) return;
_value = value!;
OnSettingChanged();
OnPropertyChanged(nameof(Value));
if (AutoSave)
Save();
}
}
///
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);
}
///
public string Name { get; }
///
public bool HasChanged => CoreJson.Serialize(Value) != _pluginSettingEntity.Value;
///
public bool AutoSave { get; set; }
///
public void RejectChanges()
{
Value = CoreJson.Deserialize(_pluginSettingEntity.Value);
}
///
public void Save()
{
if (!HasChanged)
return;
_pluginSettingEntity.Value = CoreJson.Serialize(Value);
_pluginRepository.SaveSetting(_pluginSettingEntity);
OnSettingSaved();
}
///
public event EventHandler? SettingChanged;
///
public event EventHandler? SettingSaved;
}