using System;
using System.Collections.Generic;
namespace Cthangover.Mods.Rpg
{
///
/// Builds the event list of every map from event files read in mod load order.
/// A new id is appended; an id already present (ignoring case) is replaced in
/// place, so the later file wins and keeps the original's drawing order. Mods
/// load after their dependencies, so the engine's replacement rule holds:
/// ship the same event id and declare depends on the owner to replace
/// it, ship a new id to add to any mod's map.
///
/// Pure data, so the merge rules are tested without a mod set.
///
public class RpgMapEventMerge
{
/// Events per map id (case-insensitive).
public Dictionary> Maps { get; } = new(StringComparer.OrdinalIgnoreCase);
///
/// Adds the events of one file of for map ;
/// each event gets and .
/// Returns the ids that replaced an earlier event.
///
public List Add(string map, string modId, string file, IEnumerable events)
{
var replaced = new List();
if (!Maps.TryGetValue(map, out var list))
{
list = new List();
Maps[map] = list;
}
foreach (var mapEvent in events ?? Array.Empty())
{
if (mapEvent == null || string.IsNullOrWhiteSpace(mapEvent.Id))
continue;
mapEvent.ModId = modId;
mapEvent.File = file;
var index = list.FindIndex(e => string.Equals(e.Id, mapEvent.Id, StringComparison.OrdinalIgnoreCase));
if (index < 0)
{
list.Add(mapEvent);
continue;
}
list[index] = mapEvent;
replaced.Add(mapEvent.Id);
}
return replaced;
}
}
}