using CloudBuilder.Core.Application.Builders;
using CloudBuilder.Core.Application.Packs;
using CloudBuilder.Core.Extensions;
using CloudBuilder.Core.Service;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace CloudBuilder.Core.DependencyInjection.Task
{
    [PackLevel(20)]
    public class ScheduleTaskPack : CloudBuilderPack
    {
        /// <summary>
        /// 获取 模块级别
        /// </summary>
        public override PackLevel Level => PackLevel.Business;

        /// <summary>
        /// 获取 模块启动顺序，模块启动的顺序先按级别启动，级别内部再按此顺序启动
        /// </summary>
        public override int Order => 2;

        /// <summary>
        /// 将服务添加到依赖注入服务容器中
        /// </summary>
        /// <param name="services">依赖注入服务容器</param>
        /// <returns></returns>
        public override IServiceCollection AddServices(IServiceCollection services, CloudBuilderBuilder builder)
        {
            var baseType = typeof(IScheduleTask);

            var allAssemblies = CloudBuilderBuilder.GetAssemblies();

            var types = allAssemblies
           .SelectMany(a => a.DefinedTypes)
           .Select(type => type.AsType())
           .Where(type => type != baseType && type.HasImplementedRawGeneric(baseType))
           .Where(x => x.IsClass).ToList();


            foreach (var implementType in types)
            {
                //使用TryAddScoped可以避免同一个接口注册多个实现

                //使用AddScoped可以同一个接口注册多个实现
                //即使容器中原本就有IOrder服务，也会再添加一个IOrder服务进去，这样一来容器中就会存在多个IOrder服务
                //在需要获取服务的地方注入IOrder服务时，默认会得到最后一个注册的IOrder服务实例
                //IEnumerable<IOrder> orders获取所有的IOrder服务
                services.AddScoped(baseType, implementType);
            }

            return services;
        }


    }
}