using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace GreenTree.Maschinenbestellungen.Domain.Extension
{
    public static class DbSetExtension
    {
        /// <summary>
        /// Removes a sequence of entities from a specific DbSet filtered by a predicate
        /// </summary>
        /// <typeparam name="TEntity">Entity type.</typeparam>
        /// <param name="dbSet">Database DbSet.</param>
        /// <param name="expression">Filter expression.</param>
        public static void RemoveWhere<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> expression)
            where TEntity : class
        {
            var entities = dbSet
                .Where(expression);

            dbSet.RemoveRange(entities);
        }

        /// <summary>
        /// Removes a sequence of entities from a specific DbSet filtered by a predicate and inserts a set of new entities for them
        /// </summary>
        /// <typeparam name="TEntity">Entity type.</typeparam>
        /// <param name="dbSet">Database DbSet.</param>
        /// <param name="expression">Filter expression.</param>
        /// <param name="newEntities">New entities.</param>
        public static void ReplaceWhere<TEntity>(this DbSet<TEntity> dbSet, Expression<Func<TEntity, bool>> expression,
            IEnumerable<TEntity> newEntities)
            where TEntity : class
        {
            RemoveWhere(dbSet, expression);

            dbSet.AddRange(newEntities);
        }
    }
}
