summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs
blob: 7dee09ca8f2909130e91f211dbb74f1733fd5a4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Collections.Generic;
using System.Linq;
using StardewModdingAPI.Framework.StateTracking.Comparers;
using StardewValley;

namespace StardewModdingAPI.Framework.StateTracking.Snapshots
{
    /// <summary>A frozen snapshot of the tracked game locations.</summary>
    internal class WorldLocationsSnapshot
    {
        /*********
        ** Fields
        *********/
        /// <summary>A map of tracked locations.</summary>
        private readonly Dictionary<GameLocation, LocationSnapshot> LocationsDict = new(new ObjectReferenceComparer<GameLocation>());


        /*********
        ** Accessors
        *********/
        /// <summary>Tracks changes to the location list.</summary>
        public SnapshotListDiff<GameLocation> LocationList { get; } = new();

        /// <summary>The tracked locations.</summary>
        public IEnumerable<LocationSnapshot> Locations => this.LocationsDict.Values;


        /*********
        ** Public methods
        *********/
        /// <summary>Update the tracked values.</summary>
        /// <param name="watcher">The watcher to snapshot.</param>
        public void Update(WorldLocationsTracker watcher)
        {
            // update location list
            this.LocationList.Update(watcher.IsLocationListChanged, watcher.Added, watcher.Removed);

            // remove missing locations
            foreach (var key in this.LocationsDict.Keys.Where(key => !watcher.HasLocationTracker(key)).ToArray())
                this.LocationsDict.Remove(key);

            // update locations
            foreach (LocationTracker locationWatcher in watcher.Locations)
            {
                if (!this.LocationsDict.TryGetValue(locationWatcher.Location, out LocationSnapshot snapshot))
                    this.LocationsDict[locationWatcher.Location] = snapshot = new LocationSnapshot(locationWatcher.Location);

                snapshot.Update(locationWatcher);
            }
        }
    }
}