using System;
using System.Linq;
using System.Windows;
using Prism.Events;
using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.UserInterfaceElements.DatabaseVerifier;
using Valg.EVA.Skanning.UserInterfaceElements.ErrorHandling;
using Application = System.Windows.Forms.Application;

namespace Valg.EVA.Skanning.Sample.Startup
{
    public class MainWindowInitializer : IMainWindowInitializer, IStartableComponent
    {
        private readonly ITypedFactory typedFactory;
        private readonly IGenericStartupErrorHandler genericStartupErrorHandler;
        private readonly IEventAggregator eventAggregator;

        public MainWindowInitializer(ITypedFactory typedFactory, IGenericStartupErrorHandler genericStartupErrorHandler, IEventAggregator eventAggregator)
        {
            this.typedFactory = typedFactory;
            this.genericStartupErrorHandler = genericStartupErrorHandler;
            this.eventAggregator = eventAggregator;
        }

        public void Start()
        {
            var databaseVerifiedEvent = eventAggregator.GetEvent<DatabaseConsistencyVerifiedEvent>();
            databaseVerifiedEvent.Subscribe(TryInitializeMainWindow);
        }

        private void TryInitializeMainWindow(DatabaseConsistencyVerifiedEventArgs eventArgs)
        {
            try
            {
                var mainWindow = typedFactory.Create<IMainWindow>();
                mainWindow.Initialize(eventArgs.IsElectionConfigInstalled);
                var isKioskMode = Environment.GetCommandLineArgs().Contains("-kiosk");
                mainWindow.ShowWindow(isKioskMode);
            }
            catch (Exception exception)
            {
                genericStartupErrorHandler.HandleCriticalStartupError(exception);
                Environment.Exit(0);
            }
        }
    }
}

