using System.Collections.Generic;
using System.Linq;
using Valg.EVA.Skanning.Contracts;
using Valg.EVA.Skanning.Scan.ReadSoftContracts.Model;
using Valg.EVA.Skanning.ServicesModel.Internal.Validation;

namespace Valg.Eva.Skanning.Scan.Presentation.ReadSoftModel.FieldValidators
{
    public class MarkDecrFieldValidator : IFieldValidator
    {
        private readonly FillPercentageRangeChecker rangeChecker;

        public MarkDecrFieldValidator(FillPercentageRangeCheckerFactory rangeCheckerFactory)
        {
            rangeChecker = rangeCheckerFactory.GetStrikeoutRangeChecker();
        }

        public ScannableFieldType FieldType { get { return ScannableFieldType.MarkDecr; } }
        public bool IsFieldValid(ScannedField field, IEnumerable<ScannedField> alreadyAddedFields)
        {
            return IsMarkDecrFillPercentageValid(int.Parse(field.Value)) 
                && !HasCandidateRenumberAndDeletion(field.FieldIndex, alreadyAddedFields.ToList());
        }

        private bool HasCandidateRenumberAndDeletion(int fieldIndex, IEnumerable<ScannedField> alreadyAddedFields)
        {
            return alreadyAddedFields.Any(x => x.IsRenumberField() && x.FieldIndex == fieldIndex);
        }

        private bool IsMarkDecrFillPercentageValid(int fillPercentage)
        {
            return rangeChecker.IsInsideRange(fillPercentage);
        }
    }
}
