using System.Collections.ObjectModel;
using Valg.EVA.Skanning.ServicesModel.Internal.SystemSettings;
using Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.Candidate;
using Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.RenumberStrikeout;

namespace Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.PageXOfY
{
    public class CandidateSectionHelper
    {
        public static ObservableCollection<CandidateViewModel> GetCandidatesForPage(ObservableCollection<CandidateViewModel> allCandidates, CandidateSection section)
        {
            var candidatesForPage = new ObservableCollection<CandidateViewModel>();

            var startIndex = section.FirstCandidateInSectionRank - 1;
            int currentIndex = startIndex;

            while (currentIndex < allCandidates.Count &&
                   currentIndex >= startIndex
                   && IsCurrentIndexWithinEndIndex(currentIndex, section.LastCandidateInSectionRank))
            {
                candidatesForPage.Add(allCandidates[currentIndex]);
                currentIndex++;
            }

            return candidatesForPage;
        }

        public static ObservableCollection<RenumberStrikeoutViewModel> GetRenumberStrikeoutsForPage(ObservableCollection<RenumberStrikeoutViewModel> allRenumberStrikeouts, CandidateSection section)
        {
            var renumberStrikeoutsForPage = new ObservableCollection<RenumberStrikeoutViewModel>();

            var startIndex = section.FirstCandidateInSectionRank - 1;
            int currentIndex = startIndex;

            while (currentIndex < allRenumberStrikeouts.Count &&
                   currentIndex >= startIndex
                   && IsCurrentIndexWithinEndIndex(currentIndex, section.LastCandidateInSectionRank))
            {
                renumberStrikeoutsForPage.Add(allRenumberStrikeouts[currentIndex]);
                currentIndex++;
            }

            return renumberStrikeoutsForPage;
        }

        public static bool IsCurrentIndexWithinEndIndex(int currentIndex, int? lastCandidateOnPageRankFromSection)
        {
            if (!lastCandidateOnPageRankFromSection.HasValue)
            {
                return true;
            }

            return currentIndex <= (lastCandidateOnPageRankFromSection - 1);
        }

        public static CandidateSection[] GetDefaultCandidatePageSections()
        {
            return new[]
            {
                new CandidateSection {SectionIndex = 0, FirstCandidateInSectionRank = 1, LastCandidateInSectionRank = 30},
                new CandidateSection {SectionIndex = 1, FirstCandidateInSectionRank = 31, LastCandidateInSectionRank = 61},
                new CandidateSection {SectionIndex = 2, FirstCandidateInSectionRank = 62, LastCandidateInSectionRank = null}
            };
        }
    }
}
