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

namespace Valg.EVA.Skanning.Commands.SetBoxCompletelyScanned
{
    public class SetBoxCompletelyScannedCommandHandler : IHandleCommandsWithReturnValue<SetBoxCompletelyScannedCommand, SetBoxCompletelyScannedResult>
    {
        private readonly ICountingWriteableRepository countingWriteableRepository;
        private readonly TransactionScopeFactory transactionScopeFactory;

        public SetBoxCompletelyScannedCommandHandler(ICountingWriteableRepository countingWriteableRepository, TransactionScopeFactory transactionScopeFactory)
        {
            this.countingWriteableRepository = countingWriteableRepository;
            this.transactionScopeFactory = transactionScopeFactory;
        }

        public void HandleCommand(SetBoxCompletelyScannedCommand command)
        {
            using (var scope = transactionScopeFactory.GetTransactionScope())
            {
                try
                {
                    if (command.IsInEmergencyMode)
                    {
                        countingWriteableRepository.MarkCountingAsProcessedDuringEmergencMode(command.CountingId);
                    }

                    countingWriteableRepository.UpdateBoxCountingState(command.BarcodeLong, command.BarcodeShort, command.CountingId, BoxCountingState.ScanComplete, command.ConcurrencyToken, BoxCountingState.Scanning, command.ChangedBy);
                    scope.Complete();
                    CommandResult = SetBoxCompletelyScannedResult.Ok();
                }
                catch (DBConcurrencyException ex)
                {
                    EvaSkanningEventSource.Log.ConcurrencyError(GetType().ToString(), ex.ToString());
                    CommandResult = SetBoxCompletelyScannedResult.BoxIsDeleted();
                }
            }
        }

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