// Copyright © 2017-2018 Atomic Software, LLC. All Rights Reserved.
// See LICENSE.md for full license information.


using Atom.Core.Collections;
using Atom.Core.Diagnostics;
using System;

namespace Atom.Core.Networking.Messages
{
    public static class MessageHandlerLoader
    {
        private static readonly Dictionary<MessageProtocol, MessageHandlerDelegate> Handlers = new Dictionary<MessageProtocol, MessageHandlerDelegate>();

        public static void LoadHandlers()
        {
            foreach (var Handler in AtomAssembly.GetMethodsWithAttribute<MessageHandlerAttribute>())
            {
                var Attribute = Handler.First;
                var Method = Handler.Second;

                if (Handlers.ContainsKey(Attribute.Protocol))
                {
                    Log.Warning($"Duplicate message handler found [{Attribute.Protocol}]");
                    Handlers.Remove(Attribute.Protocol);
                }

                Handlers.Add(Attribute.Protocol, (MessageHandlerDelegate) Delegate.CreateDelegate(typeof(MessageHandlerDelegate), Method));
            }

            Log.Info($"Loaded {Handlers.Count} message handler(s)");
        }

        public static bool CanGetHandler(MessageProtocol protocol, out MessageHandlerDelegate handler)
        {
            return Handlers.TryGetValue(protocol, out handler);
        }
    }
}
