use anyhow::*;
use std::fs;
use std::process::Command;

fn main() {
    println!("Hello, world!");
}

fn abspath(f: &str) -> String {
    fs::canonicalize(f)
        .unwrap()
        .to_str()
        .unwrap()
        .to_string()
}

fn do_qrtool_test(cmd: &str, f: &str) -> Result<()> {
    if f.ends_with(".DS_Store") {
        return Ok(());
    }
    let qrtool = abspath("../alg/qrtool");
    let out = Command::new(&qrtool)
        .arg(cmd)
        .arg(f)
        .current_dir("../alg")
        .output()?;
    if out.status.code().context("code")? != 0 {
        println!("{qrtool} {cmd} {f}");
        bail!("cmd failed");
    }
    Ok(())
}

fn list_files(p: &str) -> Vec<String> {
    let mut ret = Vec::new();
    let paths = fs::read_dir(p).unwrap();
    for path in paths {
        let ap = abspath(&path.unwrap().path().display().to_string());
        let md = fs::metadata(&ap).unwrap();
        if md.file_type().is_dir() {
            continue;
        }
        ret.push(ap);
    }
    ret
}

#[test]
fn test_roi() {
    let files = list_files("../dataset/roi");
    println!("roi test with {} files", files.len());
    for i in &files {
        if i.ends_with(".roi.jpg") {
            continue;
        }
        do_qrtool_test("roi", i).unwrap();
    }
}

#[test]
fn test_angle() {
    let files = list_files("../dataset/angle");
    println!("angle test with {} files", files.len());
    for i in &files {
        do_qrtool_test("angle", i).unwrap();
    }
}

#[test]
fn test_topleft() {
    let files = list_files("../dataset/topleft");
    println!("topleft test with {} files", files.len());
    for i in &files {
        if i.ends_with(".topleft.jpg") {
            continue;
        }
        do_qrtool_test("topleft", i).unwrap();
    }
}
