using System.Reflection;
using Volo.Abp.Modularity;

// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
    public static class ServiceCollectionExtensions
    {
        public static void AddPluginApplications(this IServiceCollection services, string pluginPath = "")
        {
            if (string.IsNullOrWhiteSpace(pluginPath))
            {
                pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
            }
            var assemblies = GetAssembliesFromFolder(pluginPath);

            foreach (var assembly in assemblies)
            {
                var applicationServiceType = assembly.GetTypes()
                    .FirstOrDefault(a => a.IsClass && !a.IsAbstract && typeof(AbpModule).IsAssignableFrom(a));
                services.AddApplication(applicationServiceType);
            }
        }

        private static IEnumerable<Assembly> GetAssembliesFromFolder(string folderPath)
        {
            var directory = new DirectoryInfo(folderPath);
            if (!directory.Exists) return [];

            var files = directory.GetFiles("*.dll");

            var assemblies = new List<Assembly>();
            foreach (var file in files)
            {
                try
                {
                    var assembly = Assembly.LoadFrom(file.FullName);
                    assemblies.Add(assembly);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}");
                }
            }

            return assemblies;
        }
    }
}
