use crate::context::Context;
use crate::model::text::fmt::{to_colored_json, to_colored_yaml, NestedTextViewIndent, TextView};
use crate::model::Format;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::sync::Arc;
pub struct LogHandler {
ctx: Arc<Context>,
}
impl LogHandler {
pub fn new(ctx: Arc<Context>) -> Self {
Self { ctx }
}
pub fn log_serializable<S: Serialize>(&self, value: &S) {
match self.ctx.format() {
Format::Json => {
println!("{}", serde_json::to_string(value).unwrap());
}
Format::PrettyJson => {}
Format::Yaml => {
println!("---\n{}", serde_yaml::to_string(value).unwrap());
}
Format::PrettyYaml => {}
Format::Text => {
println!("{}", serde_json::to_string_pretty(value).unwrap());
}
}
}
pub fn log_view<View: TextView + Serialize + DeserializeOwned>(&self, view: &View) {
match self.ctx.format() {
Format::Json => {
println!("{}", serde_json::to_string(view).unwrap());
}
Format::PrettyJson => {
if self.ctx.should_colorize() {
println!("{}", to_colored_json(view).unwrap());
} else {
println!("{}", serde_json::to_string(view).unwrap());
}
}
Format::Yaml => {
println!("---\n{}", serde_yaml::to_string(view).unwrap());
}
Format::PrettyYaml => {
if self.ctx.should_colorize() {
println!("---\n{}", to_colored_yaml(view).unwrap());
} else {
println!("---\n{}", serde_yaml::to_string(view).unwrap());
}
}
Format::Text => {
view.log();
}
}
}
pub fn nested_text_view_indent(&self) -> NestedTextViewIndent {
NestedTextViewIndent::new(self.ctx.format())
}
}