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

namespace Siger.Middlelayer.WmsRepository
{
    public class WmsRepositoryFactory
    {
        private static WmsRepositoryFactory _factory;

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

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

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