using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Valg.EVA.Skanning.Contracts;
using Valg.EVA.Skanning.Scan.ReadSoftContracts.Model;

namespace Valg.Eva.Skanning.Scan.Presentation.ReadSoftModel.FieldValidators
{
    public class CandidateRenumberFieldValidator : IFieldValidator
    {
        public ScannableFieldType FieldType { get { return ScannableFieldType.Ca_renumber; } }
        public bool IsFieldValid(ScannedField field, IEnumerable<ScannedField> alreadyAddedFields = null)
        {
            return
                IsPositiveIntergerWithNoLeadingZero(field.Value) &&
                !RenumberToSameNumber(field.FieldIndex, field.Value) &&
                !CandidateRenumberValidationHelper.IsRenumberUsed(field.Value, alreadyAddedFields) &&
                !HasCandidateRenumberAndDeletion(field.FieldIndex, alreadyAddedFields);
        }

        private bool RenumberToSameNumber(int fieldNumber, string renumberCandidate)
        {
            return fieldNumber.ToString(CultureInfo.InvariantCulture) == renumberCandidate;
        }

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

        private static bool IsPositiveIntergerWithNoLeadingZero(string value)
        {
            int result;
            if (!int.TryParse(value, out result))
                return false;
            return result > 0 && value[0] != '0';
        }
    }
}
