use crate::settings::pong_settings::TaskType;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::thread::sleep;
use std::time::Duration;
#[derive(Serialize, Clone, Debug)]
pub struct TargetStatus {
pub task_type: TaskType,
pub target: String,
pub elapsed: i64,
}
pub struct Targets {
tx: mpsc::Sender<TargetStatus>,
statuses: Arc<Mutex<HashMap<String, TargetStatus>>>,
}
impl Targets {
pub fn new() -> Self {
let (tx, rx) = mpsc::channel::<TargetStatus>();
let statuses = Arc::new(Mutex::new(HashMap::<String, TargetStatus>::new()));
let statuses_clone = statuses.clone();
thread::spawn(move || {
loop {
{
let new_status = rx.recv().unwrap();
let key = Self::calc_key(&new_status.task_type, &new_status.target);
let mut statuses = statuses_clone.lock().unwrap();
let old_status = statuses.get(&key);
if old_status.is_none() || old_status.unwrap().elapsed != new_status.elapsed {
statuses.insert(key, new_status);
}
}
sleep(Duration::from_secs(1)); }
});
Self { tx, statuses }
}
pub fn calc_key(task_type: &TaskType, target: &str) -> String {
format!("{} {}", task_type, target)
}
pub fn clone_tx(&self) -> mpsc::Sender<TargetStatus> {
self.tx.clone()
}
pub fn get_all(&self) -> HashMap<String, TargetStatus> {
self.statuses.lock().unwrap().clone()
}
}