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

namespace Siger.Middlelayer.AccRepository
{
    public class AccRepositoryFactory
    {
        private static AccRepositoryFactory _factory;

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

        public void Initialization(IServiceCollection services)
        {
            DiRepositories(services, typeof(IAccRepositoryBase<>));
            RepositoryFactory.Instance.DiRepositories(services, typeof(IApiConfigRepositoryBase<>));
            services.AddDbContext<ApiConfigDbContext>();
            services.AddDbContext<ApiAccDbContext>();
            services.AddScoped(typeof(IUnitOfWork), typeof(AccUnitOfWork));
        }

        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);
                        }
                    }
                }
            }
        }
    }
}
