using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace BarContracts.DI
{
	public class ServiceDependencyContainer : IDependencyContainer
	{
		private ServiceProvider? _serviceProvider;
		private readonly ServiceCollection _serviceCollection;

		public ServiceDependencyContainer()
		{
			_serviceCollection = new ServiceCollection();
		}

		public void AddLogging(Action<ILoggingBuilder> Configure)
		{
			_serviceCollection.AddLogging(Configure);
		}

		public void RegisterType<T, U>(bool IsSingleton) where U : class, T where T : class
		{
			if (IsSingleton)
			{
				_serviceCollection.AddSingleton<T, U>();
			}
			else
			{
				_serviceCollection.AddTransient<T, U>();
			}
			
			_serviceProvider = null;
		}

		public void RegisterType<T>(bool IsSingleton) where T : class
		{
			if (IsSingleton)
			{
				_serviceCollection.AddSingleton<T>();
			}
			else
			{
				_serviceCollection.AddTransient<T>();
			}
			
			_serviceProvider = null;
		}

		public T Resolve<T>()
		{
			if (_serviceProvider == null)
			{
				_serviceProvider = _serviceCollection.BuildServiceProvider();
			}
			
			return _serviceProvider.GetService<T>()!;
		}
	}
}
