using System.Windows;
using Valg.EVA.Skanning.ContainerExtensions;
using Valg.EVA.Skanning.Resources;
using Valg.EVA.Skanning.Resources.Language;
using Valg.EVA.Skanning.ServicesModel.ServiceContracts.TransferCounting.Write;
using Valg.EVA.Skanning.UserInterfaceElements.LightBox;
using Valg.EVA.Skanning.UserInterfaceElements.MessageBox;
using Prism.Events;

namespace Valg.EVA.Skanning.JobManagement.Startup.UI.Counting
{
    public class TransferErrorsPresenter : ITransferErrorsPresenter
    {
        private readonly IEventAggregator eventAggregator;
        private readonly ITypedFactory typedFactory;
        private const string ResourcePrefix = "JobManagementLanguageString.Transfer_Error_";

        public TransferErrorsPresenter(IEventAggregator eventAggregator, ITypedFactory typedFactory)
        {
            this.eventAggregator = eventAggregator;
            this.typedFactory = typedFactory;
        }

        public void ShowError(TransferCountingFailureDetails failureDetails)
        {
            var message = GetErrorMessage(failureDetails.ErrorCode, false);
            if (string.IsNullOrEmpty(message))
            {
                message = failureDetails.Message;
            }
            var resultDialog = typedFactory.Create<IMessageBox>();

            if (failureDetails.Exception != null)
            {
                resultDialog.Initialize(
                JobManagementLanguageString.Transfer_Error_Title,
                message,
                string.Empty,
                MessageBoxType.Warning,
                errorException: failureDetails.Exception != null ? new[] { failureDetails.Exception } : null);
            }
            else
            {
                resultDialog.Initialize(
                    JobManagementLanguageString.Transfer_Error_Title,
                    message,
                    string.Empty,
                    MessageBoxType.Warning);
            }

            var eventArgs = new LightBoxEventArgs(resultDialog as Window);
            eventAggregator.GetEvent<ShowLightBoxEvent>().Publish(eventArgs);
        }

        public static string GetErrorMessage(string errorCode, bool wrapNonExistingWithGeneral = true)
        {
            var resource = LanguageResource.GetText(ResourcePrefix + errorCode);

            if (wrapNonExistingWithGeneral && resource == null)
            {
                resource = LanguageResource.GetText(ResourcePrefix + TransferCountingFailureDetails.generalError);
            }

            return resource;
        }
    }
}
