using Microsoft.Extensions.DependencyInjection;
using Kit.Helpers.Log;
using Kit.Helpers.Repository.Xml;
using Kit.Helpers.Service;

namespace Kit.Helpers.Config;

public static class DependencyInjectionXmlUpdateItems
{
    public static IServiceCollection AddModuleXmlVersionService(this IServiceCollection services)
    {
        services.AddSingleton<IXmlFileVersionRepository, XmlFileVersionRepository>();
        services.AddSingleton<IXmlVersionService, XmlVersionService>();
        services.RegisterUpdateItemsViaReflection();

        return services;
    }

    private static void RegisterUpdateItemsViaReflection(this IServiceCollection services)
    {
        var interfaceType = typeof(IXmlVersionUpdateItem);

        var callStackLog = new CallStackLog();
        callStackLog.BeginCall("Get Assemblies");
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        callStackLog.EndCall();

        callStackLog.BeginCall("Get All Implementations");
        IEnumerable<Type> implementationTypes = assemblies.SelectMany(x => x.GetTypes()).Where(t => interfaceType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
        callStackLog.EndCall();

        var message = callStackLog.LogMessage;

        implementationTypes.ForEach(implementationType => services.AddTransient(interfaceType, implementationType));
    }
}