using System.Reflection;

namespace Atomx.Admin.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class DataServiceExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddDataService(this IServiceCollection services)
        {
            // 从 appsettings.json 中获取包含配置规则的程序集信息
            string assemblies = "Atomx.Data";
            //集中注册服务
            if (!string.IsNullOrEmpty(assemblies))
            {

                foreach (var assembly in assemblies.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var dic = new DataServiceExtensionHelper().GetClassName(assembly);
                    //集中注册服务
                    foreach (var item in dic)
                    {
                        foreach (var typeArray in item.Value)
                        {
                            services.AddScoped(typeArray, item.Key);
                        }
                    }
                }

            }

            return services;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class DataServiceExtensionHelper
    {
        /// <summary>  
        /// 获取程序集中的实现类对应的多个接口
        /// </summary>  
        /// <param name="assemblyName">程序集</param>
        public Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!string.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.Load(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces().Where(p => p.Name.Contains("Service")).ToArray();
                    if (interfaceType.Any())
                    {
                        result.Add(item, interfaceType);
                    }
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }
    }
}
