using System;
using Valg.EVA.Skanning.Contracts.CommonEnums;
using Valg.EVA.Skanning.ServicesModel.Internal.Validation;
using Valg.EVA.Skanning.ServicesModel.ServiceContracts.Verification.Read;

namespace Valg.EVA.Skanning.ServicesModel.Internal.Verification
{
    public static class CandidatePersonVoteMapper
    {
        public static CandidatePersonVoteReadOnly MapSingleCandidatePersonVote(BallotPaperFieldValueAggregate personVotesAggregate, FillPercentageRangeChecker rangeChecker)
        {
            var isCreatedFirstTimeByVerifier = personVotesAggregate.OriginalValue == null && (personVotesAggregate.CurrentValue.ValueSourceType == ValueSourceType.Verify);
            var personVote = new CandidatePersonVoteReadOnly(personVotesAggregate.CurrentValue.FieldIndex.GetValueOrDefault(),
                personVotesAggregate.DidOriginalValueNeedVerification(),
                personVotesAggregate.CurrentValue.NeedsVerification,
                IsPersonVotedAsGivenByCorrection(personVotesAggregate),
                IsPersonVotedAsInterpretedByScanner(personVotesAggregate, rangeChecker),
                personVotesAggregate.CurrentValue.BallotPaperFieldId, isCreatedFirstTimeByVerifier);
            return personVote;
        }

        private static bool? IsPersonVotedAsInterpretedByScanner(BallotPaperFieldValueAggregate b, FillPercentageRangeChecker rangeChecker)
        {
            if (b.OriginalValue != null)
            {
                var originalValueInt = Convert.ToInt32(b.OriginalValue.Value);
                return rangeChecker.IsInsideRange(originalValueInt);
            }

            return null;
        }

        private static bool? IsPersonVotedAsGivenByCorrection(BallotPaperFieldValueAggregate b)
        {
            if (b.CurrentValue != null && b.CurrentValue.ValueSourceType == ValueSourceType.Verify)
            {
                return b.CurrentValue.Value == ScannerFieldValueTemplateValues.PersonVoteIsGiven.ToString();
            }

            return null;
        }
    }
}
