using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Unity.Interception.Utilities;

using Valg.EVA.Skanning.Verify.Startup.Preview;
using Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.VerifiableViewModelsCollection;

namespace Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.PageXOfY
{
    public class BallotPageCollection
    {
        private readonly ObservableCollection<BallotPage> pages = new ObservableCollection<BallotPage>();

        public IEnumerable<IPagedVerificationViewModel> PagedViewModels
        {
            get { return pages.Select(p => p.ViewModel); }
        }
        public IEnumerable<PageXOfYNavigationTooltip> PageNavigationTooltips
        {
            get { return pages.Select(p => p.Tooltip); }
        }
        public IEnumerable<PreviewBallotPaperImageViewModel> PreviewImagesViewModels
        {
            get { return pages.Select(p => p.Preview); }
        }

        public IReadOnlyList<BallotPage> Pages => pages;

        public void Add(IPagedVerificationViewModel viewModel, PageXOfYNavigationTooltip tooltip, PreviewBallotPaperImageViewModel preview)
        {
            var page = new BallotPage(viewModel, tooltip, preview);
            Add(page);
        }

        private void Add(BallotPage page)
        {
            pages.Add(page);
            page.PageNumber = pages.Count;
        }

        public List<BallotPage> RemoveType(Type type)
        {
            var matchingPages = pages.Where(p => p.ViewModel.GetType() == type).ToList();
            matchingPages.ForEach(p => pages.Remove(p));
            ReOrderPages();
            return matchingPages;
        }

        private void ReOrderPages()
        {
            var pageIndex = 1;
            foreach (var p in pages)
            {
                p.PageNumber = pageIndex++;
            }
           
        }

        public IViewModelWithVerifiableContent[] GetVerificationFields()
        {
            return GetVerificationFields(pages);
        }

        public static IViewModelWithVerifiableContent[] GetVerificationFields(IEnumerable<BallotPage> pages)
        {
            var fields = pages
               .SelectMany(p => p.ViewModel?.GetVerificationFields().Where(f => f.NeededVerification))
               .ToArray();
            var order = 0;
            fields.ForEach(f => f.VerificationOrder = order++);
            return fields;           
        }

        public void Remove(BallotPage ballotPage)
        {
            pages.Remove(ballotPage);
        }
    }
}
