/*!
# `ansi2tex` command line tool

The ansi2tex tool provides command line access to the `ANSI2TeX` conversion
system for converting a text file containing ANSI escape sequences into a
compatible TeX file.

It reads the input text on standard input and write the TeX code on standard
output.

Example:
```sh
ansi2tex <ansi.txt >output.tex
```

The output TeX code can be enclosed into an environment using the -e option:
```sh
ansi2tex -e myenv <ansi.txt >output.tex
```
*/

#[doc(hidden)]
mod ansi_color;
#[doc(hidden)]
mod ansi_err;
#[doc(hidden)]
mod ansi_parser;
#[doc(hidden)]
mod ansi_visitor;
#[doc(hidden)]
mod ansi2tex;

use ansi2tex::ANSI2TeX;
use ansi_parser::ANSIParser;
use clap::Parser;
use std::error::Error;
use std::io::{stdin, stdout, BufReader, BufWriter};

#[doc(hidden)]
fn verbosity_to_level(v: u8) -> log::LevelFilter {
  match v {
    0 => log::LevelFilter::Warn,
    1 => log::LevelFilter::Info,
    2 => log::LevelFilter::Debug,
    _ => log::LevelFilter::Trace,
  }
}

#[doc(hidden)]
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {

  /// Increase verbosity (-v, -vv, -vvv)
  #[arg(short, long, action = clap::ArgAction::Count)]
  verbose: u8,

  /// Set a TeX environment that will be used to enclose the output.
  #[arg(short, long)]
  env: Option<String>,
}

#[doc(hidden)]
fn main() -> Result<(), Box<dyn Error>> {

  // Read command line arguments
  let args = Args::parse();

  // Initialize logger with verbosity level
  env_logger::Builder::new()
        .filter_level(verbosity_to_level(args.verbose))
        .init();

  // Create converter instance
  let mut buf_writer = BufWriter::new(stdout());
  let mut conv = ANSI2TeX::new(&mut buf_writer);
  
  // Set TeX environment
  if let Some(env) = args.env {
    conv = conv.env(&env);
  }

  let mut buf_reader = BufReader::new(stdin());
  let mut parser = ANSIParser::new(&mut buf_reader);

  // Parse
  parser.accept(&mut conv)?;

  Ok(())
}
