using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using FootwearTest.Services;
using FootwearTest.ViewModels;
using FootwearTest.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

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

        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
        }

        public override void OnFrameworkInitializationCompleted()
        {
            _serviceProvider = ConfigureServices();
            var logger = _serviceProvider.GetRequiredService<ILogger<App>>();
            var settings = _serviceProvider.GetRequiredService<DeviceSettings>();
            logger.LogInformation(
                "Application services configured. UseSimulator={UseSimulator}, Host={Host}, Port={Port}, PollIntervalMs={PollIntervalMs}",
                settings.UseSimulator,
                settings.Host,
                settings.Port,
                settings.PollIntervalMilliseconds);

            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                desktop.MainWindow = new MainWindow
                {
                    DataContext = _serviceProvider.GetRequiredService<MainWindowViewModel>(),
                };
            }

            base.OnFrameworkInitializationCompleted();
        }

        private static ServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection();
            services.AddLogging(builder => builder.AddSerilog(dispose: false));
            services.AddSingleton<DeviceSettings>();
            services.AddSingleton<TestFormulaService>();
            services.AddSingleton<TestRunRepository>();
            services.AddSingleton<ReportService>();
            services.AddSingleton<ExcelReportService>();
            services.AddSingleton<IDeviceClient>(provider =>
            {
                var settings = provider.GetRequiredService<DeviceSettings>();
                var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
                return settings.UseSimulator
                    ? new SimulatedDeviceClient(settings, loggerFactory.CreateLogger<SimulatedDeviceClient>())
                    : new ModbusTcpDeviceClient(settings, loggerFactory.CreateLogger<ModbusTcpDeviceClient>());
            });

            services.AddSingleton<DashboardViewModel>();
            services.AddSingleton<MethodAViewModel>();
            services.AddSingleton<MethodBViewModel>();
            services.AddSingleton<HistoryViewModel>();
            services.AddSingleton<ReportViewModel>();
            services.AddSingleton<SettingsViewModel>();
            services.AddSingleton<MainWindowViewModel>();
            return services.BuildServiceProvider();
        }
    }
}
