use crate::prelude::*;

use super::GraphSerializer;

use futures::{StreamExt, TryFutureExt};
use tokio::io::AsyncWriteExt;

#[derive(Debug, Clone)]
pub struct State {}

#[derive(Debug)]
pub struct NTriplesSerializer {}

impl Default for NTriplesSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl NTriplesSerializer {
    pub fn new() -> Self {
        Self {}
    }
}

impl GraphSerializer for NTriplesSerializer {
    async fn write_all<G, W>(&self, graph: G, writer: &mut W) -> Result<(), GraphError>
    where
        G: GraphView,
        W: AsyncWriteExt + Unpin + Send,
    {
        let mut stream = graph.stream().await?;
        while let Some(triple_res) = stream.next().await {
            match triple_res {
                Ok(triple) => writer
                    .write_all(format!("{triple}\n").as_bytes())
                    .await
                    .map_err(SourceError::Io)?,
                Err(e) => return Err(e),
            };
        }
        Ok(())
    }
}
