using Valg.EVA.Skanning.Repositories.Counting;

namespace Valg.EVA.Skanning.Commands.SaveBallotPaperVerifications
{
    public class EnsureEmergencyModeFlagFilter : IFilter<SaveBallotPaperVerificationsCommand, Empty>
    {
        private readonly ICountingRepository countingRepository;
        private readonly ICountingWriteableRepository countingWriteableRepository;

        public EnsureEmergencyModeFlagFilter(ICountingRepository countingRepository, ICountingWriteableRepository countingWriteableRepository)
        {
            this.countingRepository = countingRepository;
            this.countingWriteableRepository = countingWriteableRepository;
        }

        public Empty Execute(SaveBallotPaperVerificationsCommand command)
        {
            EnsureEmergencyModeFlagIsSet(command);
            return Empty.Value;
        }

        private void EnsureEmergencyModeFlagIsSet(SaveBallotPaperVerificationsCommand command)
        {
            if (command.IsInEmergencyMode)
            {
                var counting = countingRepository.GetCountingByBallotPaperId(command.BallotPaperId);
                if (!counting.IsProcessedInEmergencyMode)
                    countingWriteableRepository.MarkCountingAsProcessedDuringEmergencMode(counting.Id);
            }
        }
    }
}
