using System; using System.Collections.Generic; using Netcode; namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { internal class NetListWatcher : BaseDisposableWatcher, ICollectionWatcher where TValue : class, INetObject { /********* ** Fields *********/ /// The field being watched. private readonly NetList> Field; public TKey Key { get; } /// The pairs added since the last reset. private readonly IList AddedImpl = new List(); /// The pairs removed since the last reset. private readonly IList RemovedImpl = new List(); /********* ** Public methods *********/ /// Construct an instance. /// The field to watch. public NetListWatcher(NetList> field, TKey key) { this.Field = field; this.Key = key; field.OnElementChanged += this.OnElementChanged; field.OnArrayReplaced += this.OnArrayReplaced; } public bool IsChanged => this.AddedImpl.Count > 0 || this.RemovedImpl.Count > 0; public IEnumerable Added => this.AddedImpl; public IEnumerable Removed => this.RemovedImpl; public void Dispose() { if (!this.IsDisposed) { this.Field.OnElementChanged -= this.OnElementChanged; this.Field.OnArrayReplaced -= this.OnArrayReplaced; } base.Dispose(); } public void Reset() { this.AddedImpl.Clear(); this.RemovedImpl.Clear(); } public void Update() { this.AssertNotDisposed(); } /********* ** Private methods *********/ private void OnArrayReplaced(NetList> list, IList before, IList after) { this.AddedImpl.Clear(); this.RemovedImpl.Clear(); foreach(var obj in after) this.AddedImpl.Add(obj); foreach(var obj in before) this.RemovedImpl.Add(obj); } private void OnElementChanged(NetList> list, int index, TValue oldValue, TValue newValue) { /* checks for stack addition / subtraction changing stacks does not fire off an element changed event if ((oldValue != null && newValue != null) && oldValue.CompareTo(newValue) < 0) this.AddedImpl.Add(newValue); //Stack Removed from if ((oldValue != null && newValue != null) && oldValue.CompareTo(newValue) > 0) this.RemovedImpl.Add(newValue); */ if(newValue!=null) this.AddedImpl.Add(newValue); if(oldValue!=null) this.RemovedImpl.Add(oldValue); } } }