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

namespace Siger.Middlelayer.IMSRepository
{
    public class IMSRepositoryFactory
    {
        private static IMSRepositoryFactory _factory;

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

        public void Initialization(IServiceCollection services)
        {
            RepositoryFactory.Instance.DiRepositories(services, typeof(IApiConfigRepositoryBase<>));
            WmsRepositoryFactory.Instance.DiRepositories(services, typeof(IWMSRepositoryBase<>));
            DiRepositories(services, typeof(IIMSRepositoryBase<>));
            services.AddDbContext<ApiConfigDbContext>();
            services.AddDbContext<ApiIMSDbContext>();
            services.AddDbContext<ApiWmsDbContext>();
            services.AddScoped(typeof(IUnitOfWork), typeof(IMSUnitOfWork));
        }

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