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.DeleteCounting
{
    public class DeleteCountingCommandHandler : IHandleCommandsWithReturnValue<DeleteCountingCommand, DeleteCountingCommandResult>
    {
        private readonly ICountingWriteableRepository countingWriteableRepository;
        private readonly TransactionScopeFactory transactionScopeFactory;

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

        public void HandleCommand(DeleteCountingCommand command)
        {
            CommandResult = new DeleteCountingCommandResult();

            using (var scope = transactionScopeFactory.GetTransactionScope())
            {
                try
                {
                    countingWriteableRepository.MarkCountingAsDeleted(command.CountingId, command.CountingConcurrencyToken, command.ModifiedBy);

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

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