using System;
using System.Collections.Generic;

namespace GameMessage
{
    public static class MessageManager
    {
        private static Dictionary<int, Type> messageTypeDic = new Dictionary<int, Type>();

        private static Dictionary<Type, int> opcodeDic = new Dictionary<Type, int>();

        /// <summary>
        /// 注册
        /// </summary>
        public static void Register()
        {
            if (messageTypeDic.Count > 0)
            {
                return;
            }

            Type messageType = typeof(MessageAttribute);

            Type[] types = typeof(MessageManager).Assembly.GetTypes();
            foreach (var type in types)
            {
                object[] att = type.GetCustomAttributes(messageType, false);
                if (att.Length == 0)
                {
                    continue;
                }

                MessageAttribute messageAttribute = att[0] as MessageAttribute;
                if (messageAttribute == null)
                    continue;

                int opcode = messageAttribute.Opcode;
                if (opcode != 0)
                {
                    messageTypeDic.Add(opcode, type);
                    opcodeDic.Add(type,opcode);
                    
                    //Log.Debug("添加消息:" + opcode + "," + type);
                }
            }
        }

        public static Type GetType(int opcode)
        {
            if (!messageTypeDic.TryGetValue(opcode, out var type))
            {
                throw new Exception($"OpcodeType not found type: {opcode}");
            }

            return type;
        }

        public static int GetOpcode(Type type)
        {
            if (!opcodeDic.TryGetValue(type,out var opcode))
            {
                throw new Exception($"OpcodeType not found opcode: {type}");
            }
            
            return opcode;
        }
    }
}