using System.Threading.Tasks;
using Valg.EVA.Skanning.Contracts.CommonEnums;
using Valg.EVA.Skanning.Entity.SqlConnection;
using Valg.EVA.Skanning.Repositories.Transfers;

namespace Valg.EVA.Skanning.Commands.SaveResultFileForTransfer
{
    public class SaveResultFileForTransferAsyncCommandHandler : IHandleAsyncCommandsWithResult<SaveResultFileForTransferCommand, int>
    {
        private readonly ITransferWriteableRepository transferWriteableRepository;
        private readonly TransactionScopeFactory transactionScopeFactory;

        public SaveResultFileForTransferAsyncCommandHandler(ITransferWriteableRepository transferWriteableRepository, TransactionScopeFactory transactionScopeFactory)
        {
            this.transferWriteableRepository = transferWriteableRepository;
            this.transactionScopeFactory = transactionScopeFactory;
        }

        public async Task<int> HandleCommandAsync(SaveResultFileForTransferCommand command)
        {
            int result;
            using (var scope = transactionScopeFactory.GetTransactionScope())
            {
                result = await transferWriteableRepository.InsertTransferAsync(command.TransferJobId, TransferState.FileTransferStarted, command.UserName, command.ResultArchive);
                scope.Complete();
            }

            return result;
        }
    }
}
