using CloudBuilder.Core.Application.Builders;
using CloudBuilder.Core.Application.Packs;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.DatabaseAccessor;
using CloudBuilder.Core.DependencyInjection.EFCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection.Extensions;
using CloudBuilder.Core.Service;
using CloudBuilder.Core.Extensions;

namespace CloudBuilder.Core.DependencyInjection.Policy
{
    [PackLevel(10)]
    public class PolicyPack : 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)
        {
            //注入Policy
            var baseType = typeof(IPolicy);

            var allAssemblies = CloudBuilderBuilder.GetAssemblies();

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


            foreach (var implementType in types)
            {
                services.TryAddKeyedScoped(implementType, implementType.Name);
            }

            return services;
        }


    }
}