use crate::{
    BusinessProcessModelAndNotation,
    message_flow::BPMNMessageFlow,
    traits::{objectable::BPMNObject, processable::Processable, writable::Writable},
};
use anyhow::anyhow;
use quick_xml::events::{BytesStart, Event};

impl Writable for BPMNMessageFlow {
    fn write<W: std::io::Write>(
        &self,
        x: &mut quick_xml::Writer<W>,
        _parent: &dyn Processable,
        bpmn: &BusinessProcessModelAndNotation,
    ) -> anyhow::Result<()> {
        let source_id = bpmn
            .global_index_2_element(self.source_global_index)
            .ok_or_else(|| anyhow!("source not found"))?
            .id();
        let target_id = bpmn
            .global_index_2_element(self.target_global_index)
            .ok_or_else(|| anyhow!("target not found"))?
            .id();

        x.write_event(Event::Empty(
            BytesStart::new("messageFlow").with_attributes([
                ("id", self.id.as_str()),
                ("sourceRef", source_id),
                ("targetRef", target_id),
            ]),
        ))?;
        Ok(())
    }
}
