using CloudBuilder.Core.Authorization;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CloudBuilder.Core.DependencyInjection.EFCore
{
    public class RegistEntityHelper
    {
        public static void AddMasterEntityType(ModelBuilder builder, string _assemblyName)
        {
            var eType = typeof(IEntity<>);
            AddMasterEntityType(builder, _assemblyName, eType);
        }

        public static void AddSecondaryEntityType(ModelBuilder builder, string _assemblyName)
        {
            var eType = typeof(ISecondary);
            AddMasterEntityType(builder, _assemblyName, eType);
        }

        public static void AddMasterEntityType(ModelBuilder builder, string _assemblyName, Type eType)
        {
            var mType = typeof(IEntity<>);
            var sType = typeof(ISecondary);

            var entityTypes = Assembly.Load(new AssemblyName(_assemblyName)).GetTypes()
                .Where(type => !string.IsNullOrWhiteSpace(type.Namespace))
                .Where(type => type.GetTypeInfo().IsClass)
                .Where(type => type.GetTypeInfo().BaseType != null)
                .Where(type => type.HasImplementedRawGeneric(eType)).ToList();

            if (eType == mType) entityTypes = entityTypes.Where(type => !type.HasImplementedRawGeneric(sType)).ToList();

            NotMappedAttribute notMapped = null; 
            foreach (var entityType in entityTypes)
            {
                //排除实体类标记[NotMapped]
                notMapped = entityType.GetCustomAttribute<NotMappedAttribute>();
                if (notMapped != null) continue;

                if (builder.Model.FindEntityType(entityType) != null)
                    continue;
                builder.Model.AddEntityType(entityType);
            }
        }

    }
}
