/*!
# `ansi2html` command line tool

The ansi2html tool provides command line access to the `ANSI2HTML` conversion
system for converting an imput text file containing ANSI escape sequences into 
HTML code.

It reads the input text on standard input and writes the HTML code on standard
output.

Example:
```sh
ansi2html <ansi.txt >output.html
*/

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

use ansi2html::ANSI2HTML;
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,

  /// Class of enclosing element
  #[arg(short, long)]
  class: 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 = ANSI2HTML::new(&mut buf_writer);
  if let Some(class) = args.class {
    conv.set_class(&class);
  }

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

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

  Ok(())
}
