using System.Reflection;

namespace BarContracts.DI
{
	public static class ServiceProviderLoader
	{
		public static IImplementationExtension? GetImplementationExtension()
		{
			IImplementationExtension? Source = null;
			
			var Files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
			foreach (var File in Files.Distinct())
			{
				Assembly Asm = Assembly.LoadFrom(File);
				foreach (var Type in Asm.GetExportedTypes())
				{
					if (Type.IsClass && typeof(IImplementationExtension).IsAssignableFrom(Type))
					{
						if (Source == null)
						{
							Source = (IImplementationExtension)Activator.CreateInstance(Type)!;
						}
						else
						{
							var NewSource = (IImplementationExtension)Activator.CreateInstance(Type)!;
							
							if (NewSource.Priority > Source.Priority)
							{
								Source = NewSource;
							}
						}
					}
				}
			}
			
			return Source;
		}

		private static string TryGetImplementationExtensionsFolder()
		{
			var WorkingDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
			while (WorkingDirectory != null && !WorkingDirectory.GetDirectories("ImplementationExtensions", SearchOption.AllDirectories).Any(x => x.Name == "ImplementationExtensions"))
			{
				WorkingDirectory = WorkingDirectory.Parent;
			}
			
			return $"{WorkingDirectory?.FullName}\\ImplementationExtensions";
		}
	}
}
