using System.Windows;
using CamBooth.App.Core.AppSettings;
using CamBooth.App.Core.Logging;
using CamBooth.App.Features.Camera;
using CamBooth.App.Features.PhotoPrismUpload;
using CamBooth.App.Features.PictureGallery;
using EDSDKLib.API.Base;
using EOSDigital.API;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CamBooth.App;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private IServiceProvider? _serviceProvider;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var configuration = BuildConfiguration();
        var services = new ServiceCollection();

        RegisterServices(services, configuration);

        _serviceProvider = services.BuildServiceProvider();

        StartBackgroundServices();

        _serviceProvider.GetRequiredService<MainWindow>().Show();
    }

    protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
    {
        TryShutdownCamera("OnSessionEnding");
        base.OnSessionEnding(e);
    }

    protected override void OnExit(ExitEventArgs e)
    {
        try
        {
            _serviceProvider?.GetService<PhotoPrismUploadQueueService>()
                ?.StopAsync().Wait(TimeSpan.FromSeconds(10));
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error stopping upload service: {ex.Message}");
        }

        TryShutdownCamera("OnExit");

        try
        {
            (_serviceProvider as IDisposable)?.Dispose();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error disposing service provider: {ex.Message}");
        }

        base.OnExit(e);
    }


    private static IConfiguration BuildConfiguration()
    {
        var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

        var builder = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("Core/AppSettings/app.settings.json", optional: false, reloadOnChange: true);

        if (environment == "Development")
            builder.AddJsonFile("Core/AppSettings/app.settings.dev.json", optional: true, reloadOnChange: true);

        return builder.Build();
    }


    private static void RegisterServices(ServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton(configuration);
        services.AddSingleton<Logger>();
        services.AddSingleton<AppSettingsService>();
        services.AddSingleton<PictureGalleryService>();
        services.AddSingleton<CameraService>();
        services.AddSingleton<PhotoPrismAuthService>();
        services.AddSingleton<PhotoPrismUploadService>();
        services.AddSingleton<PhotoPrismUploadQueueService>();
        services.AddSingleton<MainWindowViewModel>();
        services.AddTransient<MainWindow>();

        RegisterCameraApi(services, configuration);
    }


    private static void RegisterCameraApi(ServiceCollection services, IConfiguration configuration)
    {
        var useMockCamera = bool.Parse(configuration["AppSettings:UseMockCamera"] ?? "false");
        try
        {
            ICanonAPI canonApi = useMockCamera ? new CanonAPIMock() : new CanonAPI();
            services.AddSingleton(canonApi);
        }
        catch (DllNotFoundException ex)
        {
            MessageBox.Show(
                $"EDSDK konnte nicht geladen werden. Verwende Mock-Kamera.\n\nFehler: {ex.Message}",
                "DLL nicht gefunden", MessageBoxButton.OK, MessageBoxImage.Warning);

            services.AddSingleton<ICanonAPI>(new CanonAPIMock());
        }
    }


    private void StartBackgroundServices()
    {
        try
        {
            var logger = _serviceProvider!.GetRequiredService<Logger>();
            var uploadQueueService = _serviceProvider.GetRequiredService<PhotoPrismUploadQueueService>();
            uploadQueueService.Start();
            uploadQueueService.ScanAndQueueFailedUploads();
            logger.Info("PhotoPrism UploadQueueService gestartet");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error starting background services: {ex.Message}");
        }
    }

    private void TryShutdownCamera(string source)
    {
        try
        {
            var cameraService = _serviceProvider?.GetService<CameraService>();
            cameraService?.CloseSession();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error closing camera session ({source}): {ex.Message}");
        }
    }
}