use std::fmt::Write as _;
use std::ops::Range;
use f_office_xml::NodeId;
use super::build::{
content_after, copy_children, first_run_properties, holds_note_reference_in, insert_last,
open_range_in, prefix, run_text,
};
use super::{Main, NamedFault, Place};
use crate::ns::W;
use crate::reader::PartReader;
use crate::table::{Merge, RowCell, row_cells};
const NOT_COPIED: [&str; 3] = ["cnfStyle", "sectPr", "vMerge"];
pub(super) struct NewRow {
pub(super) xml: String,
pub(super) cells: Vec<(Option<String>, String)>,
}
pub(super) fn new_row(
main: &Main<'_>,
reader: &mut PartReader,
(row, place, next): (NodeId, Place, Option<NodeId>),
texts: &[String],
) -> Result<NewRow, NamedFault> {
let doc = main.doc;
let places = row_cells(reader, row);
if places
.iter()
.any(|cell| main.parent(cell.node) != Some(row))
{
return Err(NamedFault::WrappedCells);
}
if texts.len() > places.len() {
return Err(NamedFault::TooManyCells {
given: texts.len(),
cells: places.len(),
});
}
let below = next.map_or_default(|next| row_cells(reader, next));
let w = prefix(doc, row)?;
let mut cells_xml = String::new();
let mut cells = Vec::new();
for (index, place_of_cell) in places.iter().enumerate() {
let continues = continues_merge(place_of_cell, place, &below);
let text = texts.get(index).map_or("", String::as_str);
if continues && !text.is_empty() {
return Err(NamedFault::MergedCellText { cell: index + 1 });
}
let (xml, style) = new_cell(main, &w, place_of_cell.node, continues, text);
cells_xml.push_str(&xml);
cells.push((style, text.to_owned()));
}
let exceptions = copied(main, row, "tblPrEx", &w);
let properties = copied(main, row, "trPr", &w);
Ok(NewRow {
xml: format!("<{w}:tr>{exceptions}{properties}{cells_xml}</{w}:tr>"),
cells,
})
}
fn continues_merge(cell: &RowCell, place: Place, below: &[RowCell]) -> bool {
match place {
Place::Before => cell.merge == Some(Merge::Continue),
Place::After => {
cell.merge.is_some()
&& below
.iter()
.any(|next| next.start == cell.start && next.merge == Some(Merge::Continue))
}
}
}
fn new_cell(
main: &Main<'_>,
w: &str,
cell: NodeId,
continues: bool,
text: &str,
) -> (String, Option<String>) {
let mut properties = main
.doc
.child(cell, W, "tcPr")
.map_or_default(|tcpr| copy_children(main, tcpr, &|child| not_copied(main, child)));
if continues {
let _ = write!(properties, "<{w}:vMerge/>");
}
let properties = wrapped(w, "tcPr", &properties);
let (paragraph, style) = one_paragraph(main, w, cell, text);
(format!("<{w}:tc>{properties}{paragraph}</{w}:tc>"), style)
}
fn one_paragraph(main: &Main<'_>, w: &str, cell: NodeId, text: &str) -> (String, Option<String>) {
let doc = main.doc;
let first = doc.child(cell, W, "p");
let ppr = first.and_then(|paragraph| doc.child(paragraph, W, "pPr"));
let style = ppr
.and_then(|ppr| doc.child(ppr, W, "pStyle"))
.and_then(|style| doc.attribute(style, Some(W), "val"))
.map(str::to_owned);
let properties =
ppr.map_or_default(|ppr| copy_children(main, ppr, &|child| not_copied(main, child)));
let properties = wrapped(w, "pPr", &properties);
let run = run(main, w, first, text);
(format!("<{w}:p>{properties}{run}</{w}:p>"), style)
}
fn run(main: &Main<'_>, w: &str, paragraph: Option<NodeId>, text: &str) -> String {
if text.is_empty() {
return String::new();
}
let formatting = paragraph
.and_then(|paragraph| first_run_properties(main, paragraph))
.unwrap_or_default();
format!("<{w}:r>{formatting}{}</{w}:r>", run_text(w, text))
}
fn copied(main: &Main<'_>, node: NodeId, local: &str, w: &str) -> String {
main.doc
.child(node, W, local)
.map_or_else(String::new, |child| {
wrapped(
w,
local,
©_children(main, child, &|grandchild| not_copied(main, grandchild)),
)
})
}
fn wrapped(w: &str, local: &str, inner: &str) -> String {
if inner.is_empty() {
String::new()
} else {
format!("<{w}:{local}>{inner}</{w}:{local}>")
}
}
fn not_copied(main: &Main<'_>, node: NodeId) -> bool {
NOT_COPIED.iter().any(|local| main.doc.is(node, W, local))
}
pub(super) fn replaced_content(
main: &Main<'_>,
node: NodeId,
properties: &str,
xml: &str,
) -> Result<((Range<usize>, String), bool), NamedFault> {
let doc = main.doc;
let removed: Vec<NodeId> = doc
.child_elements(node)
.filter(|&child| !doc.is(child, W, properties))
.collect();
if let Some(element) = open_range_in(doc, &removed) {
return Err(NamedFault::RangeEnd { element });
}
let notes = holds_note_reference_in(doc, &removed);
let span = main.span(node);
let kept = doc.child(node, W, properties).map(|child| main.span(child));
let splice = match content_after(main.bytes, &span, kept) {
Some(content) => (content, xml.to_owned()),
None => insert_last(main.bytes, span, xml),
};
Ok((splice, notes))
}
pub(super) fn new_content(
main: &Main<'_>,
(node, cell): (NodeId, bool),
text: &str,
) -> Result<(String, Option<String>), NamedFault> {
let w = prefix(main.doc, node)?;
if cell {
return Ok(one_paragraph(main, &w, node, text));
}
Ok((run(main, &w, Some(node), text), None))
}