use super::finalize_ops;
use routee_compass::{
app::{compass::CompassAppError, search::SearchAppResult},
plugin::output::{OutputPlugin, OutputPluginError},
};
use routee_compass_core::algorithm::search::SearchInstance;
pub struct FinalizeOutputPlugin {
pub id_field_name: String,
}
impl FinalizeOutputPlugin {
pub const FIELD_NAMES_AND_PATHS: &'static [(&'static str, &'static [&'static str]); 12] = &[
("origin_edge", &["request", "origin_edge"]),
("mode", &["request", "mode"]),
("origin_x", &["request", "origin_x"]),
("origin_y", &["request", "origin_y"]),
("time", &["time_bin", "max_time"]),
("isochrone", &["isochrone"]),
("population", &["request", "population"]),
("tree_edge_count", &["tree_edge_count"]),
("search_runtime", &["search_runtime"]),
("basic_summary_runtime", &["basic_summary_runtime"]),
("result_memory_usage_bytes", &["result_memory_usage_bytes"]),
("error", &["error"]),
];
pub const FLATTEN_NESTED: &'static [(&'static str, &'static str); 2] =
&[("opportunities", "opps"), ("mep", "mep")];
}
impl OutputPlugin for FinalizeOutputPlugin {
fn process(
&self,
output: &mut serde_json::Value,
_: &Result<(SearchAppResult, SearchInstance), CompassAppError>,
) -> Result<(), OutputPluginError> {
println!(
"beginning finalize with output:\n {}",
serde_json::to_string_pretty(output).unwrap()
);
let mut finalized = serde_json::Map::new();
let id = finalize_ops::get_value(output, &["request", &self.id_field_name])?;
finalized.insert(self.id_field_name.clone(), id.clone());
for (name, path) in FinalizeOutputPlugin::FIELD_NAMES_AND_PATHS.iter() {
let _insert_result = match finalize_ops::get_optional_value(output, path) {
Some(value) => finalized.insert(name.to_string(), value.clone()),
None => None,
};
}
for (name, prefix) in FinalizeOutputPlugin::FLATTEN_NESTED.iter() {
let map_kvs = finalize_ops::get_map_kvs(output, name)?;
for (k, v) in map_kvs.iter() {
let new_k = format!("{prefix}_{k}");
finalized.insert(new_k, (*v).clone());
}
}
let mut finalized_json = serde_json::json!(finalized);
std::mem::swap(output, &mut finalized_json);
Ok(())
}
}