using Netcode;
namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers
{
/// A watcher which detects changes to a net value field.
/// The value type wrapped by the net field.
/// The net field type.
internal class NetValueWatcher : BaseDisposableWatcher, IValueWatcher where TNetField : NetFieldBase
{
/*********
** Fields
*********/
/// 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 TValue PreviousValue { get; private set; }
/// The latest value.
public TValue 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(TNetField field, TValue oldValue, TValue newValue)
{
this.CurrentValue = newValue;
this.IsChanged = true;
}
}
}