using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ReportGeneration.Abstract;
using ReportGeneration.Interface;

namespace ReportGeneration.Generators.LatexInclude;

public class LatexIncludeTableGenerator : TableGeneratorBase
{
  private const string RowSuffix = @" \\ \hline";
  private static Regex _escapeRegex = new("([%_])");
  
  public LatexIncludeTableGenerator(int columns) : base(columns)
  {
  }

  public LatexIncludeTableGenerator(int columns, Stream stream) : base(columns, stream)
  {
  }

  public LatexIncludeTableGenerator(int columns, Stream stream, Encoding encoding) : base(columns, stream, encoding)
  {
  }

  protected override void OnOpen()
  {
    base.OnOpen();
    var tabular = "|l|" + string.Concat(Enumerable.Repeat("c|", Columns - 1));

    WriteLine(@$"\begin{{tabular}}{{{tabular}}}
\hline");
  }

  protected override void OnClose()
  {
    base.OnClose();
    WriteLine(@"\end{tabular}");
  }

  /// <inheritdoc />
  public override ITableGenerator AppendHeader(IEnumerable<string> row) => AppendRow(row.Select(Bold));

  /// <inheritdoc />
  public override ITableGenerator AppendRow(IEnumerable<string> row)
  {
    WriteLine(string.Join(" & ", row.Select(Escape)) + RowSuffix);
    return this;
  }

  private string Bold(string str) => $@"\textbf{{{str}}}";
  private string Escape(string str) => _escapeRegex.Replace(str, "\\$1");
}