use ansiconv::{ANSIColor, ANSIParser, ANSI2TeX};
use log::debug;
use std::error::Error;
use std::fs::{create_dir_all, read_to_string};
use std::io::{BufReader, BufWriter};
use std::path::Path;

#[test]
fn test_good_files() -> Result<(), Box<dyn Error>> {

  // Enable logging display
  env_logger::Builder::new().filter_level(log::LevelFilter::Trace).init();

  let wrk_folder = Path::new("tests/wrk");
  if ! wrk_folder.exists() {
    create_dir_all(wrk_folder)?;
  }
  debug!("wrk_folder={}", wrk_folder.display());

  for entry in glob::glob("tests/res/auto/*.txt")? {

    let ansi_file = entry?;
    let res_file = ansi_file.with_extension("tex");
    let wrk_file = wrk_folder.join(res_file.file_name().unwrap());
    debug!("wrk_file={}", wrk_file.display());

    {
      // Create converter instance
      let out_file = std::fs::OpenOptions::new().create(true).write(true)
        .truncate(true).open(&wrk_file)?;
      let mut buf_writer = BufWriter::new(out_file);
      let mut conv = ANSI2TeX::new(&mut buf_writer)
        .fg_default_color(ANSIColor::new(255,255,255));
      debug!("Converter created.");

      // Create parser instance
      let in_file = std::fs::OpenOptions::new().read(true).open(ansi_file)?;
      let mut buf_reader = BufReader::new(in_file);
      let mut parser = ANSIParser::new(&mut buf_reader);
      debug!("Parser created.");

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

    // Check output file
    assert!(&wrk_file.exists(), "Missing file {}", wrk_file.display());
    assert!(&res_file.exists(), "Missing file {}", res_file.display());
    assert_eq!(read_to_string(&res_file).unwrap(),
               read_to_string(&wrk_file).unwrap(),
               "Files {0} and {1} differ.",
               res_file.display(), wrk_file.display());
  }

  Ok(())
}
