using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Siger.Middlelayer.Repository.Repositories;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.Middlelayer.Repository
{
    public class RepositoryFactory
    {
        private static RepositoryFactory _factory;

        public static RepositoryFactory Instance => _factory ?? (_factory = new RepositoryFactory());

        public void Initialization(IServiceCollection services)
        {
            DiRepositories(services, typeof(IApiConfigRepositoryBase<>));
            services.AddDbContext<ApiConfigDbContext>();
            services.AddScoped(typeof(IUnitOfWork), typeof(ApiConfigUnitOfWork));
        }

        public void DiRepositories(IServiceCollection services, Type moduleType)
        {
            foreach (Type type in Assembly.Load(GetType().Assembly.GetName()).GetTypes())
            {
                if (typeof(IRepository).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)
                {
                    var interfaces = type.GetInterfaces();
                    foreach (var i in interfaces)
                    {
                        if (!i.IsGenericType && i != typeof(IRepository) && i.Name != moduleType.Name)
                        {
                            services.AddScoped(i, type);
                        }
                    }
                }
            }
        }
    }
}
