using System.Collections.Generic;
using Valg.EVA.Skanning.Entity.ReadModel;
using Valg.EVA.Skanning.ServicesModel.ElectionConfig.DataProvider;
using Valg.EVA.Skanning.ServicesModel.Internal.Interpreter.Modifications;

namespace Valg.EVA.Skanning.ServicesModel.Internal.Interpreter
{
    public class BallotNumberInterpreter
    {
        private readonly ICandidateListDataProvider candidateListDataProvider;

        public BallotNumberInterpreter(ICandidateListDataProvider candidateListDataProvider)
        {
            this.candidateListDataProvider = candidateListDataProvider;
        }

        public void CheckBallotNumberIntegrity(BallotPaperInBoxCounting ballotPaper, IReadOnlyCollection<BallotPaperFieldValue> ballotPaperFieldValues, InterpreterModificationBuffer interpreterModificationBuffer, string boxBarcodeLong)
        {
            var ballotNumberField = ballotPaperFieldValues.GetBallotNumberField();
            if (!ballotNumberField.NeedsVerification)
            {
                if (ballotNumberField.IsBallotNumberConsistentWithBarcodeIncludingContest(boxBarcodeLong))
                {
                    if (!candidateListDataProvider.AffiliationExistsInContest(boxBarcodeLong, ballotNumberField.Value))
                    {
                        
                        
                        interpreterModificationBuffer.MarkFieldToNeedVerification(ballotNumberField);
                    }
                }
                else if (ballotNumberField.IsBallotNumberConsistentWithBarcodeExcludingContest(boxBarcodeLong))
                {
                    
                    
                    if (candidateListDataProvider.AffiliationExistsInContest(boxBarcodeLong, ballotNumberField.Value))
                    {
                        interpreterModificationBuffer.SetBallotPaperToBeMarkedAsIgnoreCandidates(ballotPaper);
                    }
                    else
                    {
                        interpreterModificationBuffer.MarkFieldToNeedVerification(ballotNumberField);
                    }
                }
                else 
                {
                    
                    interpreterModificationBuffer.MarkFieldToNeedVerification(ballotNumberField);
                }
            }
        }
    }
}
