Documentation
// Copyright © 2026 Stephan Kunz
//! Implementation of the body element type `XmlElement`.

use core::ops::Range;

use crate::{
	body::BodyNode,
	helpers::{advance_body_cursor, extract_tag_name, parse_body_node_at},
	xml_attribute::XmlAttributes,
};

/// An XML element node produced by zero-copy parsing.
///
/// Represents only actual XML elements (`<tag …>…</tag>` or `<tag/>`).
/// All string slices borrow from the original source passed to
/// [`XmlReader::parse`](crate::XmlReader::parse).
#[derive(Clone)]
pub struct XmlElement<'xml> {
	pub(crate) xml_text: &'xml str,
	/// Range of the opening tag.
	pub(crate) open: Range<usize>,
	/// Range of the closing tag, or `open.end..open.end` for self-closing.
	pub(crate) close: Range<usize>,
	/// Upper bound for sibling navigation (parent's close-tag start, or doc len).
	pub(crate) content_end: usize,
}

impl<'xml> XmlElement<'xml> {
	pub(crate) fn new(xml_text: &'xml str, open: Range<usize>, close: Range<usize>, content_end: usize) -> Self {
		XmlElement {
			xml_text,
			open,
			close,
			content_end,
		}
	}

	/// Value of attribute `name`, or `None` if the attribute is absent.
	pub fn attribute(&self, name: &str) -> Option<&'xml str> {
		self.attributes()
			.find(|a| a.name() == name)
			.map(|a| a.value())
	}

	/// Iterator over the element's attributes.
	pub fn attributes(&self) -> XmlAttributes<'xml> {
		let name_len = extract_tag_name(self.xml_text, self.open.start + 1).len();
		let attr_start = self.open.start + 1 + name_len;
		let attr_end = self.open.end.saturating_sub(1);
		XmlAttributes {
			xml_text: self.xml_text,
			pos: attr_start,
			end: attr_end,
		}
	}

	/// Tag name of this element.
	pub fn tag_name(&self) -> &'xml str {
		extract_tag_name(self.xml_text, self.open.start + 1)
	}

	/// First child node, or `None` for self-closing or empty elements.
	/// PI nodes are silently skipped.
	pub fn first_child(&self) -> Option<BodyNode<'xml>> {
		if self.close.start <= self.open.end {
			return None;
		}
		let pos = advance_body_cursor(self.xml_text, self.open.end, self.close.start)?;
		parse_body_node_at(self.xml_text, pos, self.close.start)
	}

	/// Next sibling node within the parent element, or `None`.
	/// PI nodes are silently skipped.
	pub fn next_sibling(&self) -> Option<BodyNode<'xml>> {
		let after = if self.close.is_empty() {
			self.open.end
		} else {
			self.close.end
		};
		let pos = advance_body_cursor(self.xml_text, after, self.content_end)?;
		parse_body_node_at(self.xml_text, pos, self.content_end)
	}

	/// Iterator over all direct child nodes (elements, text, comments).
	/// PI nodes are silently skipped.
	pub fn children(&self) -> XmlChildren<'xml> {
		if self.close.start <= self.open.end {
			return XmlChildren {
				xml_text: self.xml_text,
				pos: self.open.end,
				end: self.open.end,
			};
		}
		XmlChildren {
			xml_text: self.xml_text,
			pos: self.open.end,
			end: self.close.start,
		}
	}

	/// Byte range of this element in the source text.
	pub fn range(&self) -> Range<usize> {
		let end = if self.close.is_empty() {
			self.open.end
		} else {
			self.close.end
		};
		self.open.start..end
	}
}

/// Iterator over the direct child nodes of an element.
pub struct XmlChildren<'xml> {
	pub(crate) xml_text: &'xml str,
	pub(crate) pos: usize,
	pub(crate) end: usize,
}

impl<'xml> Iterator for XmlChildren<'xml> {
	type Item = BodyNode<'xml>;

	fn next(&mut self) -> Option<Self::Item> {
		let pos = advance_body_cursor(self.xml_text, self.pos, self.end)?;
		let node = parse_body_node_at(self.xml_text, pos, self.end)?;
		self.pos = match &node {
			BodyNode::Element(e) => {
				if e.close.is_empty() {
					e.open.end
				} else {
					e.close.end
				}
			}
			BodyNode::Text(t) => t.range.end,
			BodyNode::Comment(c) => c.range.end,
		};
		Some(node)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	const fn is_normal<T: Sized + Send + Sync>() {}

	#[test]
	const fn normal_types() {
		is_normal::<XmlElement>();
		is_normal::<&XmlElement>();
		is_normal::<XmlChildren>();
		is_normal::<&XmlChildren>();
	}

	#[test]
	fn first_child_returns_none_for_self_closing() {
		use crate::XmlReader;
		let root = XmlReader::parse("<root/>")
			.root_element()
			.unwrap();
		assert!(root.first_child().is_none());
	}

	#[test]
	fn children_iter_returns_none_when_body_starts_with_close_tag() {
		let xml = "<a></a></a>";
		let elem = XmlElement {
			xml_text: xml,
			open: 0..3,
			close: 3..7,
			content_end: xml.len(),
		};
		assert!(elem.first_child().is_none());
	}
}