use super::{Message, Messenger};
use std::error::Error;
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use std::thread::sleep;
use std::time::Duration;
pub mod database;
pub type Database = database::Database;
pub mod www;
pub trait Service: Send {
fn run(&self) -> Result<(), Box<dyn Error>>;
fn send(&self, msg: Message) -> Result<(), Box<dyn Error>>;
fn identify(&self) -> String;
fn set_comm_pair(&mut self, tx: Sender<Message>, rx: Receiver<Message>) -> ();
}
pub fn map_comm_pairs(service: &mut Box<dyn Service>, messenger: &mut Messenger) {
let (messenger_tx, service_rx) = mpsc::channel::<Message>();
let (service_tx, messenger_rx) = mpsc::channel::<Message>();
service.set_comm_pair(service_tx, service_rx);
messenger.set_comm_pair(service.identify(), (messenger_tx, messenger_rx));
}
pub struct TestService {
name: String,
rx: Option<Receiver<Message>>,
tx: Option<Sender<Message>>,
}
impl TestService {
pub fn new(name: &str) -> Self {
TestService {
name: name.to_string(),
rx: None,
tx: None,
}
}
}
impl Service for TestService {
fn run(&self) -> Result<(), Box<dyn Error>> {
let msg = Message::new(&self.name, "test", "This is the message content");
self.send(msg)
}
fn send(&self, msg: Message) -> Result<(), Box<dyn Error>> {
if let Some(tx) = &self.tx {
tx.send(msg)?
}
Ok(())
}
fn identify(&self) -> String {
return self.name.clone();
}
fn set_comm_pair(&mut self, tx: Sender<Message>, rx: Receiver<Message>) -> () {
self.tx = Some(tx);
self.rx = Some(rx);
}
}
#[cfg(test)]
mod tests {
use std::{fs, path::Path};
fn clean() -> Result<(), Box<dyn std::error::Error>> {
let log_dir_path = Path::new("logs/tests");
if log_dir_path.exists() {
fs::remove_dir_all(log_dir_path)?;
println!("Successfully removed {}", log_dir_path.display());
} else {
println!("Directory {} does not exist.", log_dir_path.display());
}
Ok(())
}
#[tokio::test]
async fn test_db() {}
}