using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using YGNT.Exam.Configuration;
using YGNT.Exam.EntityFrameworkCore.Seed;

namespace YGNT.Exam.EntityFrameworkCore
{
    [DependsOn(
        typeof(ExamCoreModule),
        typeof(AbpZeroCoreEntityFrameworkCoreModule))]
    public class ExamEntityFrameworkModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }

        public override void PreInitialize()
        {
            if (!SkipDbContextRegistration)
            {
                Configuration.Modules.AbpEfCore().AddDbContext<ExamDbContext>(options =>
                {
                    if (options.ExistingConnection != null)
                    {
                        ExamDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                    }
                    else
                    {
                        ExamDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                    }
                });

                //var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
                //var connectionString = configuration.GetConnectionString(QuestionLibraryConsts.ConnectionStringName);
                //Configuration.Modules.AbpEfCore()
                //    .AddDbContext<QuestionLibraryDbContext>(options =>
                //    {
                //        DbContextOptionsConfigurer.Configure(options.DbContextOptions, connectionString);
                //    });
            }
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(ExamEntityFrameworkModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }
        }
    }
}
