using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.Diagnostics;
using Valg.EVA.Skanning.Resources.Language;
using Valg.EVA.Skanning.UserInterfaceElements.MessageBox;

namespace Valg.EVA.Skanning.UserInterfaceElements.ErrorHandling
{
    public class ApplicationUnhandledExceptionHandler : IStartableComponent
    {
        private readonly ITypedFactory typedFactory;

        public ApplicationUnhandledExceptionHandler(ITypedFactory typedFactory)
        {
            this.typedFactory = typedFactory;
        }

        public void Start()
        {
            Dispatcher.CurrentDispatcher.UnhandledException += OnDispatcherUnhandledException;
        }

        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception is SqlException)
            {
                LogErrorAndShowMessageBox(e.Exception);
            }
            else
            {
                EvaSkanningEventSource.Log.UnhandledException(Process.GetCurrentProcess().ProcessName, e.Exception.ToString());

                var errorMessage = LanguageString.Error_UnhandledError;
                var messageBox = typedFactory.Create<IMessageBox>();
                messageBox.ShowWindowWhenNoParentWindow(LanguageString.Title_Error, errorMessage, string.Empty, MessageBoxType.Error, e.Exception);
            }
            
            e.Handled = true;
        }

        public static void LogErrorAndShowMessageBox(Exception exception)
        {
            var errorMessage = ErrorMessageBuilder.GetErrorMessageAndLogIfNeeded(exception);
            var errorMessageTitle = errorMessage.Title;
            if (string.IsNullOrEmpty(errorMessageTitle))
            {
                errorMessageTitle = LanguageString.Title_Error;
            }

            var messageBox = new MessageBox.MessageBox(new MessageBoxViewModel());
            messageBox.ShowWindowWhenNoParentWindow(errorMessageTitle, errorMessage.Message, errorMessage.PossibleSolutions, MessageBoxType.Error, exception);
        }
    }
}
