using Netcode;
namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers
{
/// A watcher which detects changes to a net value field.
internal class NetValueWatcher : BaseDisposableWatcher, IValueWatcher where TSelf : NetFieldBase
{
/*********
** Properties
*********/
/// The field being watched.
private readonly NetFieldBase Field;
/*********
** Accessors
*********/
/// Whether the value changed since the last reset.
public bool IsChanged { get; private set; }
/// The field value at the last reset.
public T PreviousValue { get; private set; }
/// The latest value.
public T CurrentValue { get; private set; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The field to watch.
public NetValueWatcher(NetFieldBase field)
{
this.Field = field;
this.PreviousValue = field.Value;
this.CurrentValue = field.Value;
field.fieldChangeVisibleEvent += this.OnValueChanged;
field.fieldChangeEvent += this.OnValueChanged;
}
/// Update the current value if needed.
public void Update()
{
this.AssertNotDisposed();
}
/// Set the current value as the baseline.
public void Reset()
{
this.AssertNotDisposed();
this.PreviousValue = this.CurrentValue;
this.IsChanged = false;
}
/// Stop watching the field and release all references.
public override void Dispose()
{
if (!this.IsDisposed)
{
this.Field.fieldChangeEvent -= this.OnValueChanged;
this.Field.fieldChangeVisibleEvent -= this.OnValueChanged;
}
base.Dispose();
}
/*********
** Private methods
*********/
/// A callback invoked when the field's value changes.
/// The field being watched.
/// The old field value.
/// The new field value.
private void OnValueChanged(TSelf field, T oldValue, T newValue)
{
this.CurrentValue = newValue;
this.IsChanged = true;
}
}
}