using System;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Quadarax.Foundation.Core.Data.Interface.Domain;

namespace Quadarax.Foundation.Core.Data.Domain
{
    public abstract class DataDomain : DbContext, IDomain
    {
        private MethodInfo _mtSet;
        private MethodInfo _mtgSet;
        protected DataDomain(DbContextOptions options) : base(options)
        {

        }
        public TEntitySet GetDbSet<TEntitySet>()
        {
            //TODO: comment because db constext is in this scope static
            //if (_mtSet == null)
                _mtSet = GetType().GetMethod(nameof(DbContext.Set), Type.EmptyTypes);//GetType().GetMethod("Set");
            //if (_mtgSet==null)
                _mtgSet = _mtSet.MakeGenericMethod(typeof(TEntitySet).GetGenericArguments().First());

            var returnValue = _mtgSet.Invoke(this, new object[] {});
            return (TEntitySet)returnValue;
        }

        public IUnitOfWork<TDomainContext> CreateUnitOfWork<TDomainContext>() where TDomainContext : IDomain
        {
            return new UnitOfWork<TDomainContext>((IDomainContextResolver<TDomainContext>)new DomainContextResolver<DataDomain>(this));
        }


        public void Commit()
        {
            this.SaveChanges();
        }
    }     
}
