using Valg.EVA.Skanning.Commands;
using Valg.EVA.Skanning.Commands.UpdateBallotPaperSeenStatus;
using Valg.EVA.Skanning.Entity.ReadModel;
using Valg.EVA.Skanning.Repositories.BallotPaper;
using Valg.EVA.Skanning.ServicesModel.Internal.Verification;
using BallotPaper = Valg.EVA.Skanning.ServicesModel.ServiceContracts.Verification.Read.BallotPaper;

namespace Valg.EVA.Skanning.Services.Verification
{
    public class BallotPaperToVerifyResolver : IBallotPaperToVerifyResolver
    {
        private readonly IBallotPaperRepository ballotPaperRepository;
        private readonly ICommandDispatcher commandDispatcher;
        private readonly IBallotPaperMapper mapper;

        public BallotPaperToVerifyResolver(IBallotPaperRepository ballotPaperRepository, ICommandDispatcher commandDispatcher, IBallotPaperMapper mapper)
        {
            this.ballotPaperRepository = ballotPaperRepository;
            this.commandDispatcher = commandDispatcher;
            this.mapper = mapper;
        }

        public BallotPaper GetNextBallotPaperToVerify(int boxCountingId, string userRequestingBallotPaper)
        {
            var nextBallotPaper = ballotPaperRepository.GetNextBallotPaperToVerify(boxCountingId);       

            if (nextBallotPaper != null)
            {
                AttemptSetBallotPaperIsSeen(nextBallotPaper, userRequestingBallotPaper);

                return mapper.GetBallotPaper(nextBallotPaper.BallotPaperId); 
            }

            return null;
        }

        private void AttemptSetBallotPaperIsSeen(NextBallotPaper nextBallotPaper, string user)
        {
            var command = new UpdateBallotPaperSeenStatusCommand { BallotPaperId = nextBallotPaper.BallotPaperId, ChangedBy = user, BallotPaperConcurrencyToken = nextBallotPaper.CurrentBallotPaperValuesId};
            commandDispatcher.DispatchCommand<UpdateBallotPaperSeenStatusCommand, UpdateBallotPaperSeenStatusCommandResult>(command);
        }
    }
}
