using System.Reflection;

namespace Atomx.Admin.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class FluentValidationExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddValidatorsFromAssembly(this IServiceCollection services)
        {
            var dic = new FluentValidationExtensionHelper().GetClassName("Atomx.Admin.Client.Validators");
            //集中注册服务
            foreach (var item in dic)
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }

            return services;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class FluentValidationExtensionHelper
    {
        /// <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("Validator")).ToArray();
                    if (interfaceType.Any())
                    {
                        result.Add(item, interfaceType);
                    }
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }
    }
}
