using MangaReader.Core.Data;
using MangaReader.WinUI.ViewModels;
using MangaReader.WinUI.Views;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml;
using System;
using System.IO;

namespace MangaReader.WinUI;

public partial class App : Application
{
    private Window? _window;

    public static IServiceProvider ServiceProvider { get; private set; }

    static App()
    {
        ServiceCollection services = new();

        services.AddSingleton<MainWindow>();

        services.AddSingleton<MainViewModel>();
        services.AddSingleton<SearchViewModel>();
        services.AddSingleton<LibraryViewModel>();

        services.AddMangaReader();

        ServiceProvider = services.BuildServiceProvider();

        // Ensure the database is created
        using var scope = ServiceProvider.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<MangaContext>();
        dbContext.Database.EnsureCreated();
        dbContext.Database.Migrate();
    }

    public App()
    {
        InitializeComponent();
    }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        _window = ServiceProvider.GetRequiredService<MainWindow>();
        _window.Activate();
    }
}