use std::io::Read;
use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use super::default_text_run_properties::{load_text_run_properties, XlsxTextRunProperties};
use super::paragraph::paragraph_properties::{
load_text_paragraph_properties, XlsxTextParagraphProperties,
};
use crate::{common_types::Text, excel::XmlReader, helper::extract_text_contents};
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxTextField {
pub paragraph_properties: Option<Box<XlsxTextParagraphProperties>>,
pub run_properties: Option<XlsxTextRunProperties>,
pub text: Option<Text>,
pub id: Option<String>,
pub r#type: Option<String>,
}
impl XlsxTextField {
pub(crate) fn load(reader: &mut XmlReader<impl Read>, e: &BytesStart) -> anyhow::Result<Self> {
let mut field = Self {
run_properties: None,
text: None,
paragraph_properties: None,
id: None,
r#type: None,
};
let attributes = e.attributes();
for a in attributes {
match a {
Ok(a) => {
let string_value = String::from_utf8(a.value.to_vec())?;
match a.key.local_name().as_ref() {
b"id" => {
field.id = Some(string_value);
}
b"type" => {
field.r#type = Some(string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
let mut buf: Vec<u8> = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"pPr" => {
field.paragraph_properties =
Some(Box::new(load_text_paragraph_properties(reader, e)?));
}
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"rPr" => {
field.run_properties = Some(load_text_run_properties(reader, e)?);
}
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"t" => {
field.text = Some(extract_text_contents(reader, b"t")?);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"fld" => break,
Ok(Event::Eof) => bail!("unexpected end of file at `fld`."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
return Ok(field);
}
}