using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions;
using VCommon.VEntity;

namespace VCommon.VEntityFrameworkCore
{
    public abstract class VEfDbContextBase : DbContext
    {
        protected VEfDbContextBase()
        {
            
        }

        protected VEfDbContextBase(DbContextOptions options):base(options)
        {
            
        }

        public override int SaveChanges()
        {
            foreach (var track in ChangeTracker.Entries<IHaveCreationTime>().Where(p => p.State == EntityState.Added)) track.Entity.CreationTime = DateTime.Now;
            foreach (var track in ChangeTracker.Entries<IHaveLastModificationTime>().Where(p => p.State == EntityState.Modified)) track.Entity.LastModificationTime = DateTime.Now;

            foreach (var track in ChangeTracker.Entries<ISoftDelete>().Where(p => p.State == EntityState.Deleted))
            {
                track.State = EntityState.Modified;
                track.Entity.IsAbolish = true;

                if (track.Entity is IHaveLastModificationTime lmd) lmd.LastModificationTime = DateTime.Now;
            }

            

            return base.SaveChanges();
        }


    }
}
