using System;
using System.Collections.Generic;
using System.Linq;

namespace ZionExtractor.Controllers.LegworkMethods
{
    class Position
    {
        public static List<ZionExtractor.Models.Hypothesis> Search(ZionVault.Binder.OCR.Page page,
                                                                   ZionVault.Basic.Location limit)
        {
            var words = (from areas in page.Areas
                         from paragraphes in areas.Paragraphes
                         from lines in paragraphes.Lines
                         from word in lines.Words
                         where
                             word != null
                             && (word.Location.Top >= limit.Top || limit.Top == -1)
                             && (word.Location.Bottom <= limit.Bottom || limit.Bottom == -1)
                             && (word.Location.Right <= limit.Right || limit.Right == -1)
                             && (word.Location.Left >= limit.Left || limit.Left == -1)
                         select word).ToList();

            try
            {
                List<ZionExtractor.Models.Hypothesis> list = new List<ZionExtractor.Models.Hypothesis>();
                list.Add(new ZionExtractor.Models.Hypothesis(
                            String.Join(" ", (from word in words select word.Text).ToArray()),
                            new ZionVault.Basic.Location((from word in words
                                                        select word.Location.Top).Min(),
                                (from word in words
                                 select word.Location.Right).Max(),
                                (from word in words
                                 select word.Location.Bottom).Max(),
                                (from word in words
                                 select word.Location.Left).Min()),
                            Convert.ToInt32((from word in words select word.Quality).Average())));

                return list;
            }
            catch
            {
                return new List<ZionExtractor.Models.Hypothesis>();
            }
        }
    }
}
