using System.Collections.Generic; using Netcode; namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { /// A watcher which detects changes to a net dictionary field. /// The dictionary key type. /// The dictionary value type. /// The net type equivalent to . /// The serializable dictionary type that can store the keys and values. /// The net field instance type. internal class NetDictionaryWatcher : BaseDisposableWatcher, IDictionaryWatcher where TField : class, INetObject, new() where TSerialDict : IDictionary, new() where TSelf : NetDictionary { /********* ** Fields *********/ /// The pairs added since the last reset. private readonly IDictionary PairsAdded = new Dictionary(); /// The pairs removed since the last reset. private readonly IDictionary PairsRemoved = new Dictionary(); /// The field being watched. private readonly NetDictionary Field; /********* ** Accessors *********/ /// Whether the collection changed since the last reset. public bool IsChanged => this.PairsAdded.Count > 0 || this.PairsRemoved.Count > 0; /// The values added since the last reset. public IEnumerable> Added => this.PairsAdded; /// The values removed since the last reset. public IEnumerable> Removed => this.PairsRemoved; /********* ** Public methods *********/ /// Construct an instance. /// The field to watch. public NetDictionaryWatcher(NetDictionary 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.PairsAdded.Clear(); this.PairsRemoved.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 dictionary. /// The entry key. /// The entry value. private void OnValueAdded(TKey key, TValue value) { this.PairsAdded[key] = value; } /// A callback invoked when an entry is removed from the dictionary. /// The entry key. /// The entry value. private void OnValueRemoved(TKey key, TValue value) { if (!this.PairsRemoved.ContainsKey(key)) this.PairsRemoved[key] = value; } } }