use crate::_test_support::Result;
use crate::hub::{HubEvent, get_hub};
use std::sync::Arc;
use tokio::sync::{Mutex, oneshot};
#[allow(unused)]
pub struct HubCapture {
content: Arc<Mutex<String>>,
stop_signal: Option<oneshot::Sender<()>>,
}
#[allow(unused)]
impl HubCapture {
pub fn new_and_start() -> Self {
let (stop_tx, stop_rx) = oneshot::channel();
let content = Arc::new(Mutex::new(String::new()));
let content_clone = Arc::clone(&content);
let mut rx = get_hub().subscriber();
tokio::spawn(async move {
tokio::select! {
_ = stop_rx => {
}
_ = async {
while let Ok(event) = rx.recv().await {
match event {
HubEvent::Message(msg) => {
let mut content = content_clone.lock().await;
content.push_str(&msg);
content.push('\n');
}
HubEvent::Print(print_event) => {
let mut content = content_clone.lock().await;
content.push_str(&format!("Print: {print_event:?}\n"));
}
HubEvent::Error { error } => {
let mut content = content_clone.lock().await;
content.push_str(&format!("Error: {error}\n"));
},
HubEvent::Prompt(params) => {
let mut content = content_clone.lock().await;
content.push_str(&format!("prompt: {}\n", params.message));
},
HubEvent::LuaPrint(text) => {
let mut content = content_clone.lock().await;
content.push_str(&format!("LuaPrint: {text}\n"));
}
HubEvent::Executor(exec_event)=> {
let mut content = content_clone.lock().await;
content.push_str(&format!("Exec: {exec_event} \n"));
},
HubEvent::DoExecRedo => {
let mut content = content_clone.lock().await;
content.push_str("DoExecRedo\n");
}
HubEvent::Quit => {
let mut content = content_clone.lock().await;
content.push_str("Quit\n");
},
}
}
} => {
}
}
});
Self {
content,
stop_signal: Some(stop_tx),
}
}
pub async fn into_content(mut self) -> Result<String> {
if let Some(stop_tx) = self.stop_signal.take() {
let _ = stop_tx.send(());
}
let mut content = self.content.lock().await;
let new_string = std::mem::take(&mut *content);
Ok(new_string)
}
}