﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace HAbp.Dependency
{
    public class TypeRegister : ITypeRegister
    {
        public void Register(IServiceCollection serviceCollection, Type type)
        {
            //尝试注册
            if (typeof(ISingletonDependency).IsAssignableFrom(type))
            {
                foreach (var iType in getInterfaceTypes(type))
                {
                    serviceCollection.AddSingleton(iType, type);
                }
                serviceCollection.AddSingleton(type);
            }
            else if (typeof(IScopedDependency).IsAssignableFrom(type))
            {
                foreach (var iType in getInterfaceTypes(type))
                {
                    serviceCollection.TryAddScoped(iType, type);
                }
                serviceCollection.TryAddScoped(type);
            }
            else if (typeof(ITransientDependency).IsAssignableFrom(type))
            {
                foreach (var iType in getInterfaceTypes(type))
                {
                    serviceCollection.TryAddTransient(iType, type);
                }
                serviceCollection.TryAddTransient(type);
            }

        }

        private IEnumerable<Type> getInterfaceTypes(Type type)
        {
            var iTypeName = "I" + type.Name;
            return type.GetInterfaces().Where(m =>
            {
                if (m.Name != iTypeName)
                {
                    return false;
                }
                var mInfo = m.GetTypeInfo();
                return !mInfo.IsGenericType;
            }).Distinct();
        }

        //private bool checkTypes(Type[] left, Type[] right)
        //{
        //    if (left == right)
        //    {
        //        return true;
        //    }
        //    if (left == null || right == null)
        //    {
        //        return false;
        //    }
        //    if (left.Length != right.Length)
        //    {
        //        return false;
        //    }

        //    for (int i = 0; i < left.Length; i++)
        //    {
        //        if (left[i] != right[i])
        //        {
        //            return false;
        //        }
        //    }
        //    return true;

        //}

    }
}
