using System;
using System.Collections.Generic;
namespace Jovian.EncounterSystem {
/// Dispatches instances to per-type handlers.
/// Handlers return true to stop processing remaining events.
public class EncounterResolver {
private readonly Dictionary> handlers = new();
public void Register(Func handler) where T : IEncounterEvent {
handlers[typeof(T)] = (evt, ctx) => handler((T)evt, ctx);
}
public void Unregister() where T : IEncounterEvent {
handlers.Remove(typeof(T));
}
/// Indexed iteration over — avoids the boxed enumerator
/// that an IEnumerable<T> parameter would force. Stops when a handler
/// returns true or is set.
public void Resolve(IReadOnlyList events, EncounterContext context) {
if(events == null) {
return;
}
var count = events.Count;
for(var i = 0; i < count; i++) {
var evt = events[i];
if(evt == null || context.ShouldStopEvents) {
continue;
}
if(!handlers.TryGetValue(evt.GetType(), out var handler)) {
continue;
}
if(handler(evt, context)) {
context.ShouldStopEvents = true;
}
}
}
}
}