using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Siger.Middlelayer.DncRepository.Repositories;
using Siger.Middlelayer.DncRepository.Repositories.Interface;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.Middlelayer.DncRepository
{
    public class DncRepositoryFactory
    {
        private static DncRepositoryFactory _factory;

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

        public void Initialization(IServiceCollection services)
        {
            RepositoryFactory.Instance.DiRepositories(services, typeof(IApiConfigRepositoryBase<>));
            DiRepositories(services, typeof(IDncRepositoryBase<>));
            services.AddDbContext<ApiConfigDbContext>();
            services.AddDbContext<ApiDncDbContext>();
            services.AddScoped(typeof(IUnitOfWork), typeof(DncUnitOfWork));
        }

        private 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(IRepositoryBase<>)
                                             && i != typeof(IRepository)
                                             && i.Name != moduleType.Name)
                        {
                            services.AddScoped(i, type);
                        }
                    }
                }
            }
        }
    }
}
