use super::{item_output::RenderedItemOutput, result::RenderedResult};
use crate::{element::Element, error::ItemError};
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct RenderedElementOutput<'a> {
    element: &'a Element,
    results: Vec<RenderedResult<RenderedItemOutput<'a>, &'a ItemError>>,
}

impl<'a> RenderedElementOutput<'a> {
    pub const fn element(&self) -> &'a Element {
        self.element
    }

    pub fn results(
        &self,
    ) -> impl ExactSizeIterator<Item = &RenderedResult<RenderedItemOutput<'a>, &'a ItemError>> {
        self.results.iter()
    }

    pub(crate) fn retain_error(&mut self) {
        self.results.retain(RenderedResult::is_err);
    }
}

impl<'a> From<&'a crate::element_output::ElementOutput> for RenderedElementOutput<'a> {
    fn from(output: &'a crate::element_output::ElementOutput) -> Self {
        Self {
            element: output.element(),
            results: output
                .results()
                .map(|result| result.as_ref().map(RenderedItemOutput::from).into())
                .collect(),
        }
    }
}
