using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using MossyUpdater.Services;
using MossyUpdater.ViewModels;

namespace MossyUpdater
{
    public partial class App : Application
    {
        private ServiceProvider? _serviceProvider;

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

            var services = new ServiceCollection();
            ConfigureServices(services);
            _serviceProvider = services.BuildServiceProvider();

            var mainWindow = new MainWindow
            {
                DataContext = _serviceProvider.GetRequiredService<MainViewModel>()
            };
            mainWindow.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            var mainViewModel = _serviceProvider?.GetService<MainViewModel>();
            mainViewModel?.Dispose();
            _serviceProvider?.Dispose();
            base.OnExit(e);
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<ILogger, FileLogger>();
            services.AddSingleton<ISettingsService, SettingsService>();
            services.AddSingleton<IQuotesService, QuotesService>();

            services.AddHttpClient<IDownloadService, DownloadService>(client =>
            {
                client.Timeout = TimeSpan.FromMinutes(10);
                client.DefaultRequestHeaders.Add("User-Agent", "MossyUpdater/1.0");
            });

            services.AddSingleton<MainViewModel>();
        }
    }

}
