using System;
using System.Collections.Generic;

namespace Jovian.EncounterSystem {
    /// <summary>Dispatches <see cref="IEncounterEvent"/> instances to per-type handlers.
    /// Handlers return <c>true</c> to stop processing remaining events.</summary>
    public class EncounterResolver {
        private readonly Dictionary<Type, Func<IEncounterEvent, EncounterContext, bool>> handlers = new();

        public void Register<T>(Func<T, EncounterContext, bool> handler) where T : IEncounterEvent {
            handlers[typeof(T)] = (evt, ctx) => handler((T)evt, ctx);
        }

        public void Unregister<T>() where T : IEncounterEvent {
            handlers.Remove(typeof(T));
        }

        /// <summary>Indexed iteration over <paramref name="events"/> — avoids the boxed enumerator
        /// that an <c>IEnumerable&lt;T&gt;</c> parameter would force. Stops when a handler
        /// returns <c>true</c> or <see cref="EncounterContext.ShouldStopEvents"/> is set.</summary>
        public void Resolve(IReadOnlyList<IEncounterEvent> 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;
                }
            }
        }
    }
}
