using System.Data;
using Valg.EVA.Skanning.Diagnostics;
using Valg.EVA.Skanning.Entity.SqlConnection;
using Valg.EVA.Skanning.Repositories.Counting;

namespace Valg.EVA.Skanning.Commands.RegisterBoxAsEmpty
{
    public class RegisterBoxAsEmptyCommandHandler : IHandleCommandsWithReturnValue<RegisterBoxAsEmptyCommand, RegisterBoxAsEmptyCommandResult>
    {
        private readonly ICountingWriteableRepository countingWriteableRepository;
        private readonly ICountingRepository countingRepository;
        private readonly TransactionScopeFactory transactionScopeFactory;

        public RegisterBoxAsEmptyCommandHandler(ICountingWriteableRepository countingWriteableRepository, ICountingRepository countingRepository, TransactionScopeFactory transactionScopeFactory)
        {
            this.countingWriteableRepository = countingWriteableRepository;
            this.countingRepository = countingRepository;
            this.transactionScopeFactory = transactionScopeFactory;
        }

        public void HandleCommand(RegisterBoxAsEmptyCommand command)
        {
            CommandResult = new RegisterBoxAsEmptyCommandResult();

            using (var scope = transactionScopeFactory.GetTransactionScope())
            {
                try
                {
                    if (command.IsInEmergencyMode)
                    {
                        var counting = countingRepository.GetCountingByBoxCountingId(command.BoxCountingId);
                        if (!counting.IsProcessedInEmergencyMode)
                        {
                            countingWriteableRepository.MarkCountingAsProcessedDuringEmergencMode(counting.Id);
                        }
                    }
                    countingWriteableRepository.RegisterBoxAsEmpty(command.BoxCountingId, command.BoxCountingConcurrencyToken, command.ModifiedBy);

                    scope.Complete();
                }
                catch (DBConcurrencyException ex)
                {
                    EvaSkanningEventSource.Log.ConcurrencyError(GetType().ToString(), ex.ToString());
                    CommandResult.RegisterBoxAsEmptyFailed = true;
                }
            }
        }

        public RegisterBoxAsEmptyCommandResult CommandResult { get; private set; }
    }
}
