using System.Text;

namespace Ocr.Cli.Monitor;

public class CompactCliTaskMonitor : TaskMonitor
{
  /// <inheritdoc />
  public CompactCliTaskMonitor(IEnumerable<(string? Name, Task Task)> tasks) : base(tasks) { }

  /// <inheritdoc />
  public CompactCliTaskMonitor(IEnumerable<Task> tasks) : base(tasks) { }

  #region Overrides of TaskMonitor

  /// <inheritdoc />
  protected override void OnUpdate(ICollection<(string? Name, Task Task)> tasks)
  {
    int completed = 0;
    int total = tasks.Count;

    var sb = new StringBuilder(total * 30);

    foreach (var (_, task) in tasks)
    {
      var status = task.Status;

      if (status > TaskStatus.WaitingForChildrenToComplete)
      {
        completed++;
      }

      sb.Append(task.Exception is not null ? 'X' : StatusMap[status].First());
    }

    sb.AppendLine($" ({completed}/{total})");

    Console.Clear();
    Console.Write(sb.ToString());
  }

  #endregion
}
