using Supercell.GUT.Logic.Message.Attributes; using Supercell.GUT.Titan.Message; using System.Collections.Immutable; using System.Reflection; namespace Supercell.GUT.Logic.Message; public class GUTMessageFactory : LogicMessageFactory { private readonly ImmutableDictionary s_types; public GUTMessageFactory() : base() { this.s_types = CreateMessageMap(); } public override PiranhaMessage? CreateMessageByType(int messageType) { return this.s_types.TryGetValue(messageType, out Type? type) ? Activator.CreateInstance(type) as PiranhaMessage : null; } private static ImmutableDictionary CreateMessageMap() { var builder = ImmutableDictionary.CreateBuilder(); IEnumerable types = Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.GetCustomAttribute() != null); foreach (var type in types) { VersionedMessageAttribute attribute = type.GetCustomAttribute()!; if (!builder.TryAdd(attribute.MessageType, type)) throw new Exception($"Piranha message with type {attribute.MessageType} defined twice!"); } return builder.ToImmutable(); } }