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

namespace Siger.Middlelayer.KpiRespository
{
    public  class KpiRepositoryFactory
    {
        private static KpiRepositoryFactory _factory;

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

        public void Initialization(IServiceCollection services)
        {

            RepositoryFactory.Instance.DiRepositories(services, typeof(IApiConfigRepositoryBase<>));
            DiRepositories(services, typeof(ISigerKpiBase<>));
            services.AddDbContext<ApiConfigDbContext>();
            services.AddDbContext<ApiKpiDbContext>();
            services.AddScoped(typeof(IUnitOfWork), typeof(KpiUniOfWork));
        }

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