﻿namespace Dike.EntityFrameworkCore.UnitOfWork
{
    using Microsoft.EntityFrameworkCore;

    /// <summary>
    /// Represent a class to get the current database context from the active unit of work.
    /// </summary>
    /// <typeparam name="TDbContext">The type of the database context.</typeparam>
    /// <seealso cref="Dike.EntityFrameworkCore.IDbContextProvider{TDbContext}" />
    public class UnitOfWorkDbContextProvider<TDbContext>
        : IDbContextProvider<TDbContext>
        where TDbContext : DbContext
    {
        #region Fields

        private readonly Core.Domain.UnitOfWork.ICurrentUnitOfWorkProvider _currentUnitOfWorkProvider;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="UnitOfWorkDbContextProvider{TDbContext}"/> class.
        /// </summary>
        /// <param name="currentUnitOfWorkProvider">The current unit of work provider.</param>
        public UnitOfWorkDbContextProvider(Core.Domain.UnitOfWork.ICurrentUnitOfWorkProvider currentUnitOfWorkProvider)
            => _currentUnitOfWorkProvider = currentUnitOfWorkProvider;

        #endregion Constructors

        #region Methods

        /// <summary>
        /// Gets the database context.
        /// </summary>
        /// <returns>The database context.</returns>
        public TDbContext GetDbContext()
            => GetDbContext(null);

        /// <summary>
        /// Gets the database context.
        /// </summary>
        /// <param name="multiTenancySide">The multi tenancy side.</param>
        /// <returns>TDbContext.</returns>
        public TDbContext GetDbContext(Core.MultiTenancy.MultiTenancySides? multiTenancySide)
            => _currentUnitOfWorkProvider.Current.GetDbContext<TDbContext>(multiTenancySide);

        #endregion Methods
    }
}