using System;
using System.Diagnostics;
using System.Windows.Threading;
using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.Contracts;
using Valg.EVA.Skanning.Diagnostics;
using Valg.EVA.Skanning.UserInterfaceElements.MessageBox;

namespace Valg.EVA.Skanning.UserInterfaceElements.ErrorHandling
{
    public class GenericStartupErrorHandler : IGenericStartupErrorHandler
    {
        private readonly IExceptionConverter exceptionConverter;
        private readonly ITypedFactory typedFactory;

        public GenericStartupErrorHandler(IExceptionConverter exceptionConverter, ITypedFactory typedFactory)
        {
            this.exceptionConverter = exceptionConverter;
            this.typedFactory = typedFactory;
        }

        public void HandleCriticalStartupError(Exception exception)
        {
            EvaSkanningEventSource.Log.ErrorInApplicationStartup(Process.GetCurrentProcess().ProcessName, exception.ToString());

            if (!Dispatcher.CurrentDispatcher.HasShutdownStarted)
            {
                var convertedException = exceptionConverter.Convert(exception);
                var messageBox = typedFactory.Create<IMessageBox>();
                messageBox.ShowWindowWhenNoParentWindow(convertedException.Title, convertedException.Problem, convertedException.Solution, convertedException.MessageBoxType, exception);
            }
        }
    }
}
