using System;
using System.IO;
using System.Linq;
using MediaBrowser.Common.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Server.Implementations
{
    /// 
    /// Factory class for generating new  instances.
    /// 
    public class JellyfinDbProvider
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IApplicationPaths _appPaths;
        private readonly ILogger _logger;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The application's service provider.
        /// The application paths.
        /// The logger.
        public JellyfinDbProvider(IServiceProvider serviceProvider, IApplicationPaths appPaths, ILogger logger)
        {
            _serviceProvider = serviceProvider;
            _appPaths = appPaths;
            _logger = logger;
            using var jellyfinDb = CreateContext();
            if (jellyfinDb.Database.GetPendingMigrations().Any())
            {
                _logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may take a while, do not stop Jellyfin)");
                jellyfinDb.Database.Migrate();
                _logger.LogInformation("EFCore migrations applied successfully");
            }
        }
        /// 
        /// Creates a new  context.
        /// 
        /// The newly created context.
        public JellyfinDb CreateContext()
        {
            var contextOptions = new DbContextOptionsBuilder().UseSqlite($"Filename={Path.Combine(_appPaths.DataPath, "jellyfin.db")}");
            return ActivatorUtilities.CreateInstance(_serviceProvider, contextOptions.Options);
        }
    }
}