using System;
using System.Linq;
using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.UserInterfaceElements.DatabaseVerifier;
using Prism.Events;
using Valg.EVA.Skanning.UserInterfaceElements.ErrorHandling;
using Valg.EVA.Skanning.Verify.Startup.VerifyWindow;

namespace Valg.EVA.Skanning.Verify.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 verifyWindow = typedFactory.Create<IVerifyWindow>();
                verifyWindow.Initialize(eventArgs.IsElectionConfigInstalled);
                var isKioskMode = Environment.GetCommandLineArgs().Contains("-kiosk");
                verifyWindow.ShowWindow(isKioskMode);
            }
            catch (Exception exception)
            {
                genericStartupErrorHandler.HandleCriticalStartupError(exception);
                Environment.Exit(0);
            }
        }
    }
}

