using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using Unity;
using VCommon.Ioc;
using VCommon.VEntity;
using VCommon.VEntityFrameworkCore;

namespace VCommon.VApplication.EntityFrameworkCore
{
    public abstract class VAppDbContextBase : VEfDbContextBase, ITransientIocClass
    {
        protected VAppDbContextBase()
        {
        }

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

        [Dependency]
        public IVSession VSession { get; set; }

        public override int SaveChanges()
        {
            foreach (var track in ChangeTracker.Entries<IHaveCreationUserId>().Where(p => p.State == EntityState.Added)) track.Entity.CreationUserId = VSession.UserId ?? Guid.Empty;
            foreach (var track in ChangeTracker.Entries<IHaveLastModificationUserId>().Where(p => p.State == EntityState.Modified)) track.Entity.LastModificationUserId = VSession.UserId;

            foreach (var track in ChangeTracker.Entries<ISoftDelete>().Where(p => p.State == EntityState.Deleted))
            {
                if (track.Entity is IHaveLastModificationUserId lmu) lmu.LastModificationUserId = VSession.UserId;
            }

            return base.SaveChanges();
        }
    }
}
