using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using FooEditEngine;
using FooEditEngine.Metro;

// ユーザー コントロールのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=234236 を参照してください

namespace FooEditor
{
    public sealed partial class FindFlyout : FindViewBase
    {
        MainPageViewModel mainvm;

        public FindFlyout()
        {
            this.InitializeComponent();
        }

        internal FindFlyout(MainPageViewModel vm)
            : this()
        {
            vm.DocumentCollection.CollectionChanged += DocumentCollection_CollectionChanged;
            this.mainvm = vm;
        }

        void DocumentCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.Reset();
        }

        protected override bool ShowFoundPattern
        {
            get
            {
                return AppSettings.Current.ShowFoundPattern;
            }
        }

        protected override string NotFoundInDocumentMessage
        {
            get
            {
                var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                return loader.GetString("NotFoundInDocument");
            }
        }

        protected override IEnumerable<FooTextBox> GetTextBoxs()
        {
            foreach (var docinfo in this.mainvm.DocumentCollection)
                yield return docinfo.doc.TextBox;
        }

        protected override IEnumerator<Tuple<FooTextBox, SearchResult>> GetSearchResult(Func<FooTextBox, IEnumerator<SearchResult>> FindStartFunc)
        {
            if (this.FindViewModel.AllDocuments)
            {
                foreach (var docinfo in this.mainvm.DocumentCollection)
                {
                    this.mainvm.ActiveDocument(docinfo);

                    IEnumerator<SearchResult> it = FindStartFunc(docinfo.doc.TextBox);
                    while (it.MoveNext())
                    {
                        yield return new Tuple<FooTextBox, SearchResult>(docinfo.doc.TextBox, it.Current);
                    }
                }
            }
            else
            {
                DocumentControl activeDocument = this.mainvm.DocumentCollection[this.mainvm.CurrentDocumentIndex].doc;
                IEnumerator<SearchResult> it = FindStartFunc(activeDocument.TextBox);
                while (it.MoveNext())
                {
                    yield return new Tuple<FooTextBox, SearchResult>(activeDocument.TextBox, it.Current);
                }
            }
        }
    }
}
