use std::fs;
use std::io::Write;
use anyhow::Result;
use crate::charset::Charset;
use crate::example::expl_clean_word;
use crate::*;
// =====================================================================
// FORMATTING TO HTML
// =====================================================================
pub fn format_batch<'a>(dict_idx: &DictIndex<'a>, count: usize, (i, batch): (usize, &Batch)) {
let mut f = io::BufWriter::new(
fs::File::create(format!("public/{:03}.html", i)).expect("create batch file"),
);
format_batch_to(&mut f, dict_idx, count, i, batch).expect("format batch");
}
pub fn format_batch_to<'a>(
buf: &mut impl Write,
dict_idx: &DictIndex<'a>,
count: usize,
i: usize,
batch: &Batch,
) -> Result<()> {
write!(
buf,
r#"
Batch #{:03}
"#,
i
)?;
writeln!(buf, r#"
index"#)?;
for j in 0..count {
if j != i {
writeln!(buf, r#" {:03}"#, j, j)?;
} else {
writeln!(buf, " {:03}", j)?;
}
}
writeln!(buf, r#"
"#)?;
writeln!(buf, "
Level: {}
", batch.level)?;
write!(buf, r#"
"#)?;
let mut ex_prev = Charset::default();
for ex in batch.examples.iter() {
let ex_chars = ex.chars.inter(&batch.chars);
for c in ex_chars.diff(&ex_prev).chars().iter() {
write!(
buf,
r#"{}"#,
c, c
)?;
}
ex_prev = ex_prev.union(&ex_chars);
}
writeln!(buf, r#"
"#)?;
for ex in batch.examples.iter() {
writeln!(buf, "")?;
write!(buf, r#"
"#)?;
let furi = ex.furigana_markup();
for c in furi.chars() {
let class = if batch.chars.contains(c) {
Some("char_cur")
} else if batch.chars_p1.contains(c) {
Some("char_p1")
} else if batch.chars_p2.contains(c) {
Some("char_p2")
} else if batch.chars_bad.contains(c) {
Some("char_bad")
} else {
None
};
if let Some(cls) = class {
write!(
buf,
r#"{}"#,
c, cls, c
)?;
} else {
write!(buf, "{}", c)?;
}
}
writeln!(buf, "
")?;
writeln!(buf, r#"
{}
"#, ex.en)?;
writeln!(buf, r#"Explanation"#)?;
let mut expl_batch = Vec::new();
let mut expl_all = Vec::new();
for word in ex.expl.split(|c| c == ' ' || c == '~') {
let (keb, reb) = expl_clean_word(word);
let wchars = Charset::new(keb);
if !wchars.intersects(&ex.chars) {
continue;
}
if let Some(ents) = dict_idx.get(keb) {
for ent in ents.iter() {
if let Some(s) = dict_str(keb, reb, ent) {
if wchars.intersects(&batch.chars) {
expl_batch.push(s);
} else {
expl_all.push(s);
}
}
}
}
}
for be in expl_batch {
writeln!(buf, r#"
{}
"#, be)?;
}
writeln!(buf, r#"
"#)?;
for c in ex.chars.inter(&batch.chars).chars().iter() {
writeln!(
buf,
r#"{}"#,
c, c
)?;
}
writeln!(buf, r#"