using System;
using System.Collections.Generic;
using Verse;
namespace BlaxZones
{
/// Package Store: the component's save data. See ZoneStore.
public partial class MapComponent_BlaxZones
{
///
/// Zones read from the save, held only until the Map.FinalizeLoading prefix registered them,
/// then cleared. Empty at any other time.
///
private List loadedZones = new List();
/// Zones loaded and not yet registered. Read by tests.
public IReadOnlyList LoadedZones => loadedZones;
///
/// Saving: deep-saves the Blax zones found in map.zoneManager.AllZones (the map saves zoneManager
/// before the components, Map.cs:873, 898, and the finalizer has restored the list by then).
/// Loading: reads them into loadedZones. A deleted zone is never saved again.
///
private void ExposeStore()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
List zones = ZonesToSave();
Scribe_Collections.Look(ref zones, "zones", LookMode.Deep);
return;
}
Scribe_Collections.Look(ref loadedZones, "zones", LookMode.Deep);
if (loadedZones == null)
loadedZones = new List(); // no node: a save made before Zones, or an empty component
else if (Scribe.mode == LoadSaveMode.LoadingVars)
loadedZones.RemoveAll(z => z == null); // a zone class that no longer exists logged its own error
}
/// The Blax zones registered on this map right now, in ZoneManager's order.
private List ZonesToSave()
{
var zones = new List();
try
{
List all = map?.zoneManager?.AllZones;
if (all != null)
{
foreach (Zone zone in all)
{
if (ZoneStore.IsBlaxZone(zone))
zones.Add(zone);
}
}
}
catch (Exception e)
{
ZonesLog.Once("Collecting zones to save", e);
}
return zones;
}
///
/// Called by the Map.FinalizeLoading prefix: registers every loaded zone through
/// ZoneStore.RegisterLoaded, then clears loadedZones. On an exception logs once and leaves the
/// remaining zones out of this load; the zone that threw is taken back out of the manager.
///
public void RegisterLoadedZones()
{
List zones = loadedZones;
loadedZones = new List();
if (zones == null || zones.Count == 0)
return;
Zone current = null;
try
{
foreach (Zone zone in zones)
{
if (zone == null)
continue;
current = zone;
ZoneStore.RegisterLoaded(map, zone);
current = null;
}
}
catch (Exception e)
{
ZonesLog.Once("Registering loaded zones", e);
ZoneStore.UndoRegister(map, current);
}
}
}
}