use std::sync::Arc;

use anyhow::Result;
use dittolive_ditto::{fs::TempRoot, prelude::*};

#[tokio::main]
async fn main() -> Result<()> {
    let root = TempRoot::new();
    let ditto = Ditto::open_sync(
        DittoConfig::new(
            "bus_example_app",
            DittoConfigConnect::SmallPeersOnly { private_key: None },
        )
        .with_persistence_directory(root.root_path()),
    )?;
    ditto.set_license_from_env("DITTO_LICENSE")?;

    // DittoLogger::set_minimum_log_level(LogLevel::Debug);
    ditto.update_transport_config(|tc| {
        tc.enable_all_peer_to_peer();
    });

    ditto.sync().start()?;
    let ditto = Arc::new(ditto);

    let _acceptor = ditto
        .datastreams()
        .bind_topic("example")
        .on_receive_factory(tokio::sync::mpsc::unbounded_channel)
        .finish_with(|mut stream| {
            tokio::task::spawn(async move {
                while let Some(payload) = stream.recv().await {
                    let _ = stream.message(payload).send();
                }
            });
        });

    std::future::pending::<()>().await;
    Ok(())
}
