using Ocr.Tesseract.Models;
using System.Collections.Generic;
using Tesseract;

namespace Ocr.Tesseract.Extensions;

/// <summary>
/// Extensions for the <see cref="Page"/> type
/// </summary>
public static class PageExtensions
{


  /// <summary>
  /// Retrieves the <see cref="Word"/>s in the given <paramref name="page"/>
  /// </summary>
  /// <param name="page">The <see cref="Page"/> to extract words from</param>
  /// <returns>The extracted <see cref="Word"/>s in the given <paramref name="page"/></returns>
  public static IEnumerable<Word> GetWords(this Page page)
  {
    using var iterator = page.GetIterator();
    iterator.Begin();

    do
    {
      do
      {
        do
        {
          do
          {
            var word = Word.Parse(iterator);
            if (string.IsNullOrEmpty(word.Text))
            {
              continue;
            }

            yield return word;
          } while (iterator.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
        } while (iterator.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
      } while (iterator.Next(PageIteratorLevel.Block, PageIteratorLevel.Para));
    } while (iterator.Next(PageIteratorLevel.Block));
  }
}