use problemo::*;

// First see: examples/accumulate.rs

// In order to dedup our problems we need to attach an CauseEquality or CauseComparison
// to the cause that we want to use for testing for equality between problems

// They require the cause's error to implement PartialEq or PartialOrd respectively

// See also: examples/dedup_custom.rs

gloss_error!(FileError);

fn read_files<ProblemReceiverT>(
    paths: &[&str],
    problems: &mut ProblemReceiverT,
) -> Result<Vec<String>, Problem>
where
    ProblemReceiverT: ProblemReceiver,
{
    let mut strings = Vec::default();
    for path in paths {
        if let Some(string) = std::fs::read_to_string(path)
            .via(FileError::new(path))
            .with(CauseEquality::new::<FileError>())
            .give_ok(problems)?
        {
            strings.push(string);
        }
    }
    Ok(strings)
}

fn main() {
    let mut problems = Problems::default();

    read_files(&["non-existing1.txt", "non-existing2.txt"], &mut problems).unwrap();
    read_files(&["non-existing1.txt", "non-existing2.txt"], &mut problems).unwrap();
    read_files(&["non-existing3.txt", "non-existing4.txt"], &mut problems).unwrap();

    println!("All errors:");
    for problem in &problems {
        println!("• {}", problem);
    }

    // For iter_unique() to do its job we need an CauseEquality or CauseComparison attachment
    println!("\nUnique errors:");
    for problem in problems.iter_unique() {
        println!("• {}", problem);
    }
}
