using Common.Extensions;
using ImageMagick;
using Ocr.Cli.Monitor;
using Ocr.Cli.Processor;
using Ocr.Tesseract.Screenshots.Threshold;
using System.Diagnostics.CodeAnalysis;

namespace Ocr.Cli;

public class Program
{
  public Task Run(string[] args)
  {
    Directory.Delete("results", true);
    Directory.CreateDirectory("results");

    var scans = (
      from processor in MakeThresholdVariations()
      from path in ExpandPaths(args)
      select (Key: path, Task: processor.Process(new MagickImage(path)))
    ).ToArray();

    // return new CliTaskMonitor(scans) { Interval = TimeSpan.FromMilliseconds(500) }.Run();
    return new CompactCliTaskMonitor(scans) { Interval = TimeSpan.FromMilliseconds(500) }.Run();
  }

  [SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeNotEvident")]
  private static IEnumerable<EvaluationProcessor> MakeThresholdVariations()
  {
    for (int i = 4; i <= 24; i += 4)
    {
      yield return new(new ThresholdAdaptiveProcessor(i));
    }

    for (int i = 20; i <= 80; i += 10)
    {
      yield return new(new ThresholdProcessor(i));
    }

    yield return new(new AutoThresholdProcessor(AutoThresholdMethod.Kapur));
    yield return new(new AutoThresholdProcessor(AutoThresholdMethod.OTSU));
    yield return new(new AutoThresholdProcessor(AutoThresholdMethod.Triangle));
  }

  private static IEnumerable<string> ExpandPaths(params string[] paths) =>
    paths.SelectMany(p => p.ExpandPath());

  #region Main

  public static int Main(string[] args)
  {
    Console.WriteLine("Starting up");

    try
    {
      new Program()
        .Run(args)
        .Wait();

      Console.WriteLine("Completed");
      return 0;
    }
    catch (Exception e)
    {
      Console.WriteLine(e.Message);
      return 1;
    }
  }

  #endregion
}
