use std::fmt::Display;
use std::fmt::Formatter;
use clap::ValueEnum;
use serde::Serialize;
use crate::collection::Collection;
use crate::error::Fallible;
use crate::types::date::Date;
#[derive(ValueEnum, Clone)]
pub enum StatsFormat {
Html,
Json,
}
impl Display for StatsFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
StatsFormat::Html => write!(f, "html"),
StatsFormat::Json => write!(f, "json"),
}
}
}
pub fn print_stats(directory: Option<String>, format: StatsFormat) -> Fallible<()> {
let stats = get_stats(directory)?;
match format {
StatsFormat::Html => {
eprintln!("HTML output is not implemented yet.");
}
StatsFormat::Json => {
let stats_json = serde_json::to_string_pretty(&stats)?;
println!("{}", stats_json);
}
}
Ok(())
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Stats {
cards_in_deck_count: usize,
cards_in_db_count: usize,
tex_macro_count: usize,
cards_reviewed_today_count: usize,
}
fn get_stats(directory: Option<String>) -> Fallible<Stats> {
let coll = Collection::new(directory)?;
let cards_in_db_count = coll.db.card_hashes()?.len();
let today = Date::today();
let stats = Stats {
cards_in_deck_count: coll.cards.len(),
cards_in_db_count,
tex_macro_count: coll.macros.len(),
cards_reviewed_today_count: coll.db.count_reviews_in_date(today)?,
};
Ok(stats)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::helper::create_tmp_copy_of_test_directory;
#[test]
fn test_display_stats_format() {
assert_eq!(StatsFormat::Html.to_string(), "html");
assert_eq!(StatsFormat::Json.to_string(), "json");
}
#[test]
fn test_print_stats_json() -> Fallible<()> {
let directory = create_tmp_copy_of_test_directory()?;
print_stats(Some(directory), StatsFormat::Json)?;
Ok(())
}
#[test]
fn test_get_stats() -> Fallible<()> {
let directory = create_tmp_copy_of_test_directory()?;
let stats = get_stats(Some(directory)).unwrap();
let Stats {
cards_in_deck_count,
cards_in_db_count,
tex_macro_count,
cards_reviewed_today_count,
} = stats;
assert_eq!(cards_in_deck_count, 2);
assert_eq!(cards_in_db_count, 0);
assert_eq!(tex_macro_count, 1);
assert_eq!(cards_reviewed_today_count, 0);
Ok(())
}
}