1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::domain::dtos::{
    blast_builder::BlastBuilder,
    blutils_output::BlutilsOutput,
    consensus_result::{ConsensusResult, QueryWithConsensus},
};

use std::{fs::File, io::Write, path::PathBuf};
use tracing::info;

pub fn write_blutils_output(
    results: Vec<ConsensusResult>,
    config: Option<BlastBuilder>,
    out_dir: PathBuf,
) {
    let output_file = out_dir.join("blutils.consensus.json");
    info!("");
    info!("Blutils output file:");
    info!("\t{:?}", output_file);
    info!("");

    let mut file = match File::create(output_file) {
        Err(err) => panic!("{err}"),
        Ok(res) => res,
    };

    let mut consensus_type_results = results.iter().fold(
        Vec::<QueryWithConsensus>::new(),
        |mut init, record| {
            match record {
                ConsensusResult::NoConsensusFound(res) => {
                    init.push(QueryWithConsensus {
                        query: res.query.to_owned(),
                        taxon: None,
                    });
                }
                ConsensusResult::ConsensusFound(res) => {
                    init.push(QueryWithConsensus {
                        query: res.query.to_owned(),
                        taxon: res.taxon.to_owned(),
                    })
                }
            };

            init
        },
    );

    consensus_type_results.sort_by(|a, b| a.query.cmp(&b.query));

    let config = match config {
        Some(c) => Some(BlastBuilder {
            subject_reads: PathBuf::from(c.subject_reads)
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .to_string(),
            ..c
        }),
        None => None,
    };

    match file.write_all(
        serde_json::to_string_pretty(&BlutilsOutput {
            results: consensus_type_results,
            config,
        })
        .unwrap()
        .as_bytes(),
    ) {
        Err(err) => panic!("{err}"),
        Ok(_) => (),
    };
}