using System.Collections.Generic;
using Valg.EVA.Skanning.Contracts.CommonEnums;
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 PersonalVotingAdjuster
    {
        private readonly ICandidateListDataProvider candidateListDataProvider;

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

        public void AdjustHandlingOfPersonalVotingToContest(IReadOnlyCollection<BallotPaperFieldValue> ballotPaperFieldValues, InterpreterModificationBuffer modificationBuffer, string barcodeLong, CountingType countingType)
        {
            var ballotNumberField = ballotPaperFieldValues.GetBallotNumberField();

            if (!ballotNumberField.NeedsVerification)
            {
                var consistentIncludingContest = ballotNumberField.IsBallotNumberConsistentWithBarcodeIncludingContest(barcodeLong);
                var consistentExcludingContest = ballotNumberField.IsBallotNumberConsistentWithBarcodeExcludingContest(barcodeLong);
                if ((!consistentIncludingContest && consistentExcludingContest)
                    || (countingType == CountingType.Preliminary)
                )
                {
                    if (candidateListDataProvider.AffiliationExistsInContest(barcodeLong, ballotNumberField.Value))
                    {
                        modificationBuffer.SetCorrectionFieldsToNotNeedingVerification(ballotPaperFieldValues);
                    }
                }
            }
        }

    }
}
