using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.UserInterfaceElements.DatabaseVerifier;
using System;
using System.Linq;
using System.Windows;
using Prism.Events;
using Valg.EVA.Skanning.UserInterfaceElements.ErrorHandling;
using Valg.EVA.Skanning.JobManagement.Startup.MainWindow;

namespace Valg.EVA.Skanning.JobManagement.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
            {                
                StartApplication(eventArgs.IsElectionConfigInstalled);
            }
            catch (Exception exception)
            {
                genericStartupErrorHandler.HandleCriticalStartupError(exception);
                Environment.Exit(0);
            }
        }

        private void StartApplication(bool electionConfigIsInstalled)
        {
            ShowMainWindow(electionConfigIsInstalled);
        }

        private void ShowMainWindow(bool electionConfigIsInstalled)
        {
            var isKioskMode = Environment.GetCommandLineArgs().Contains("-kiosk");
            var jobManagementMainWindow = typedFactory.Create<IMainWindow>();

            jobManagementMainWindow.Initialize(electionConfigIsInstalled);
            jobManagementMainWindow.ShowWindow(isKioskMode);
            System.Windows.Application.Current.MainWindow = (Window)jobManagementMainWindow;
        }
    }
}
