using System.Collections.Generic;
using Netcode;
namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers
{
/// A watcher which detects changes to a Netcode collection.
internal class NetCollectionWatcher : BaseDisposableWatcher, ICollectionWatcher
where TValue : INetObject
{
/*********
** Properties
*********/
/// The field being watched.
private readonly NetCollection Field;
/// The pairs added since the last reset.
private readonly List AddedImpl = new List();
/// The pairs demoved since the last reset.
private readonly List RemovedImpl = new List();
/*********
** Accessors
*********/
/// Whether the collection changed since the last reset.
public bool IsChanged => this.AddedImpl.Count > 0 || this.RemovedImpl.Count > 0;
/// The values added since the last reset.
public IEnumerable Added => this.AddedImpl;
/// The values removed since the last reset.
public IEnumerable Removed => this.RemovedImpl;
/*********
** Public methods
*********/
/// Construct an instance.
/// The field to watch.
public NetCollectionWatcher(NetCollection field)
{
this.Field = field;
field.OnValueAdded += this.OnValueAdded;
field.OnValueRemoved += this.OnValueRemoved;
}
/// Update the current value if needed.
public void Update()
{
this.AssertNotDisposed();
}
/// Set the current value as the baseline.
public void Reset()
{
this.AssertNotDisposed();
this.AddedImpl.Clear();
this.RemovedImpl.Clear();
}
/// Stop watching the field and release all references.
public override void Dispose()
{
if (!this.IsDisposed)
{
this.Field.OnValueAdded -= this.OnValueAdded;
this.Field.OnValueRemoved -= this.OnValueRemoved;
}
base.Dispose();
}
/*********
** Private methods
*********/
/// A callback invoked when an entry is added to the collection.
/// The added value.
private void OnValueAdded(TValue value)
{
this.AddedImpl.Add(value);
}
/// A callback invoked when an entry is removed from the collection.
/// The added value.
private void OnValueRemoved(TValue value)
{
this.RemovedImpl.Add(value);
}
}
}