using System;
using System.Collections.Generic;
using System.Reflection;
using MrWu.Debug;

namespace Server.Core
{
    public class CodeTypes : Singleton<CodeTypes>
    {
        /// <summary>
        /// 所有类型
        /// </summary>
        private readonly Dictionary<string, Type> allTypes = new Dictionary<string, Type>();
        
        /// <summary>
        /// 所有标记 key 表示 BaseAttribute 子类型 values 类
        /// </summary>
        private readonly UnOrderMultiMapSet<Type, Type> types = new UnOrderMultiMapSet<Type, Type>();

        public void Init(Assembly[] assemblies)
        {
            Dictionary<string, Type> addTypes = AssemblyHelper.GetAssemblyTypes(assemblies);
            foreach (var kv in addTypes)
            {
                string fullName = kv.Key;
                Type type = kv.Value;
                this.allTypes[fullName] = type;
                
                if (type.IsAbstract)
                {
                    continue;
                }
                
                // 记录所有的有BaseAttribute标记的的类型
                object[] objects = type.GetCustomAttributes(typeof(BaseAttribute), true);

                foreach (object o in objects)
                {
                    this.types.Add(o.GetType(), type);
                }
            }
            
            Debug.Info($"AllTypeCount:{this.allTypes.Count}");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="systemAttributeType"></param>
        /// <returns></returns>
        public HashSet<Type> GetTypes(Type systemAttributeType)
        {
            if (!this.types.ContainsKey(systemAttributeType))
            {
                return new HashSet<Type>();
            }

            return this.types[systemAttributeType];
        }

        public Dictionary<string, Type> GetTypes()
        {
            return allTypes;
        }

        public Type GetType(string typeName)
        {
            return this.allTypes[typeName];
        }
    }
}