using Ocr.Tesseract.Models;
using Process.Abstract;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Ocr.Tesseract;

/// <summary>
/// Filters words using regular expressions
/// </summary>
public class RegexFilter : Processor<ScanResult, ScanResult>
{
  /// <summary>
  /// <see cref="Regex"/> to apply. If the expression
  /// does not match the input, it will be removed from
  /// the output data of this processor
  /// </summary>
  public Regex Regex { get; }

  /// <summary>
  /// Constructor
  /// </summary>
  public RegexFilter(Regex regex)
  {
    Regex = regex;
  }

  #region Overrides of Processor<Word,Word>

  /// <inheritdoc />
  public override IEnumerable<ScanResult> Process(
    IEnumerable<ScanResult> inputs
  )
  {
    var matches = inputs
      .Select(kv => (Kv: kv, Match: Regex.Match(kv.Word.Text)))
      .Where(m => m.Match.Success)
      .ToArray();

    foreach (var tuple in matches)
    {
      tuple.Kv.Word.Text = tuple.Match.Value;
    }

    return matches.Select(t => t.Kv);
  }

  #endregion
}
