using Valg.EVA.Skanning.Entity.SqlConnection;
using Valg.EVA.Skanning.Repositories.Counting;

namespace Valg.EVA.Skanning.Commands.DetectDuplicatesInCounting
{
    public class DetectDuplicatesInCountingCommandHandler : IHandleCommands<DetectDuplicatesInCountingCommand>
    {
        private readonly ICountingRepository countingRepository;
        private readonly ICountingWriteableRepository countingWriteableRepository;
        private readonly TransactionScopeFactory transactionScopeFactory;

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

        public void HandleCommand(DetectDuplicatesInCountingCommand command)
        {
            using (var scope = transactionScopeFactory.GetTransactionScope())
            {
                if (countingRepository.GetDuplicatesInCounting(command.CountingId).Count > 0)
                {
                    countingWriteableRepository.UpdateDuplicatesStateInformation(command.BoxCountingId, command.ChangedBy, command.BoxCountingLastModified);
                }

                scope.Complete();
            }
        }
    }
}
