use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use std::io::Read;
use crate::{
excel::XmlReader, helper::string_to_float, raw::spreadsheet::stylesheet::color::XlsxColor,
};
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxGradientFill {
pub bottom: Option<f64>,
pub left: Option<f64>,
pub right: Option<f64>,
pub top: Option<f64>,
pub degree: Option<f64>,
pub r#type: Option<String>,
pub stop: Option<Vec<XlsxGradientStop>>,
}
impl XlsxGradientFill {
pub(crate) fn load(reader: &mut XmlReader<impl Read>, e: &BytesStart) -> anyhow::Result<Self> {
let attributes = e.attributes();
let mut fill = Self {
bottom: None,
left: None,
right: None,
top: None,
degree: None,
r#type: None,
stop: None,
};
let mut stops: Vec<XlsxGradientStop> = vec![];
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"bottom" => {
fill.bottom = string_to_float(&string_value);
}
b"left" => {
fill.left = string_to_float(&string_value);
}
b"right" => {
fill.right = string_to_float(&string_value);
}
b"top" => {
fill.top = string_to_float(&string_value);
}
b"degree" => {
fill.degree = string_to_float(&string_value);
}
b"type" => {
fill.r#type = Some(string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
let mut buf = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"stop" => {
let stop = XlsxGradientStop::load(reader, e)?;
stops.push(stop);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"gradientFill" => break,
Ok(Event::Eof) => bail!("unexpected end of file."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
fill.stop = Some(stops);
Ok(fill)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxGradientStop {
pub position: Option<f64>,
pub color: Option<XlsxColor>,
}
impl XlsxGradientStop {
pub fn load(reader: &mut XmlReader<impl Read>, e: &BytesStart) -> anyhow::Result<Self> {
let attributes = e.attributes();
let mut stop = Self {
position: None,
color: None,
};
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"position" => {
stop.position = string_to_float(&string_value);
break;
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
let mut buf = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"color" => {
let color = XlsxColor::load(e)?;
stop.color = Some(color);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"stop" => break,
Ok(Event::Eof) => bail!("unexpected end of file."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
Ok(stop)
}
}